From: Ramakrishnan Muthukrishnan Date: Thu, 23 Jul 2015 08:42:06 +0000 (+0530) Subject: refactor PeerState: Add connection handle to be part of peerstate X-Git-Url: https://git.rkrishnan.org/%5B/%5D%20/file/URI:LIT:krugkidfnzsc4/module-simplejson.tests.html?a=commitdiff_plain;h=611d238930ad59ad8fdf0cad3cd48fec6e7163ae;p=functorrent.git refactor PeerState: Add connection handle to be part of peerstate --- diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs index 70e89d8..0d70f9f 100644 --- a/src/FuncTorrent/Peer.hs +++ b/src/FuncTorrent/Peer.hs @@ -28,7 +28,8 @@ type IP = String type Port = Integer -- PeerState is a misnomer -data PeerState = PeerState { peer :: Peer +data PeerState = PeerState { handle :: Handle + , peer :: Peer , meChoking :: Bool , meInterested :: Bool , heChoking :: Bool @@ -191,13 +192,15 @@ createDummyFile path size = -- loop1 :: shake hands with all peers, find out the pieces they have, form PieceData. -- recvMsg :: Peer -> Handle -> Msg -msgLoop :: Handle -> ByteString -> PeerState -> IO () -msgLoop h pieceHash state = +msgLoop :: PeerState -> ByteString -> IO () +msgLoop state pieceHash = let numPieces = (toInteger . (`quot` 20) . BC.length) pieceHash pieceStatus = mkPieceMap numPieces pieceHash in forever $ do - msg <- getMsg h + -- if meInterested and he NOT Choking, pick a piece to download + -- and send a requestmsg. + msg <- getMsg (handle state) putStrLn $ "got a " ++ show msg case msg of BitFieldMsg bss -> do @@ -209,17 +212,18 @@ msgLoop h pieceHash state = -- download each of the piece in order UnChokeMsg -> do print msg - msgLoop h pieceHash (state {heChoking = False}) + msgLoop (state {heChoking = False}) pieceHash _ -> print msg handlePeerMsgs :: Peer -> Metainfo -> String -> (String -> IO ()) -> IO () handlePeerMsgs p m peerId logFn = do h <- handShake p (infoHash m) peerId logFn "handShake" - let state = PeerState { peer = p + let state = PeerState { handle = h + , peer = p , heInterested = False , heChoking = True , meInterested = True , meChoking = False } - msgLoop h (pieces (info m)) state + msgLoop state (pieces (info m))