type IP = String
type Port = Integer
-data PeerState = PeerState { handle :: Handle
- , amChoking :: Bool
- , amInterested :: Bool
- , peerChoking :: Bool
- , peerInterested :: Bool}
+-- PeerState is a misnomer
+data PeerState = PeerState { peer :: Peer
+ , meChoking :: Bool
+ , meInterested :: Bool
+ , heChoking :: Bool
+ , heInterested :: Bool}
-- Maintain info on every piece and the current state of it.
-- should probably be a TVar.
-- loop1 :: shake hands with all peers, find out the pieces they have, form PieceData.
-- recvMsg :: Peer -> Handle -> Msg
-msgLoop :: Handle -> ByteString -> IO ()
-msgLoop h pieceHash =
+msgLoop :: Handle -> ByteString -> PeerState -> IO ()
+msgLoop h pieceHash state =
let numPieces = (toInteger . (`quot` 20) . BC.length) pieceHash
pieceStatus = mkPieceMap numPieces pieceHash
in
BitFieldMsg bss -> do
let pieceList = bitfieldToList (unpack bss)
print pieceList
+ -- for each pieceIndex in pieceList, make an entry in the pieceStatus
+ -- map with pieceIndex as the key and modify the value to add the peer.
+
-- download each of the piece in order
+ UnChokeMsg -> do
+ print msg
+ msgLoop h pieceHash (state {heChoking = False})
_ -> print msg
handlePeerMsgs :: Peer -> Metainfo -> String -> (String -> IO ()) -> IO ()
handlePeerMsgs p m peerId logFn = do
h <- handShake p (infoHash m) peerId
logFn "handShake"
- msgLoop h (pieces (info m))
+ let state = PeerState { peer = p
+ , heInterested = False
+ , heChoking = True
+ , meInterested = True
+ , meChoking = False }
+ msgLoop h (pieces (info m)) state