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
-- 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
-- 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))