reserved = BC.replicate 8 '\0'
peerID = BC.pack peer_id
-handShake :: Peer -> ByteString -> String -> IO Handle
-handShake peer@(Peer _ ip port) infoHash peerid = do
- let hs = genHandShakeMsg infoHash peerid
+connectToPeer :: Peer -> IO Handle
+connectToPeer peer@(Peer _ ip port) = do
h <- connectTo ip (PortNumber (fromIntegral port))
hSetBuffering h LineBuffering
+ return h
+
+doHandShake :: Handle -> Peer -> ByteString -> String -> IO ()
+doHandShake h peer@(Peer _ ip port) infoHash peerid = do
+ let hs = genHandShakeMsg infoHash peerid
hPut h hs
putStrLn $ "--> handhake to peer: " ++ show peer
_ <- hGet h (length (unpack hs))
putStrLn $ "<-- handshake from peer: " ++ show peer
- return h
+ return ()
instance Binary PeerMsg where
put msg = case msg of
return $ decode $ fromStrict $ concat [lBS, msg]
sendMsg :: Handle -> PeerMsg -> IO ()
-sendMsg h msg =
- let bsMsg = toStrict $ encode msg
- in
- hPut h bsMsg
+sendMsg h msg = hPut h bsMsg
+ where bsMsg = toStrict $ encode msg
bsToInt :: ByteString -> Int
bsToInt x = fromIntegral (runGet getWord32be (fromChunks (return x)))
handlePeerMsgs :: Peer -> Metainfo -> String -> IO ()
handlePeerMsgs p m peerId = do
- h <- handShake p (infoHash m) peerId
+ h <- connectToPeer p
+ doHandShake h p (infoHash m) peerId
let state = PeerState { handle = h
, peer = p
, heInterested = False