From: Ramakrishnan Muthukrishnan Date: Mon, 27 Jul 2015 13:27:44 +0000 (+0530) Subject: refactor handshake msg X-Git-Url: https://git.rkrishnan.org/pf/content//%22?a=commitdiff_plain;h=c126fdb2399e8afdcd7523b783164e34b2439241;p=functorrent.git refactor handshake msg --- diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs index f7ccfcf..22dc48f 100644 --- a/src/FuncTorrent/Peer.hs +++ b/src/FuncTorrent/Peer.hs @@ -90,16 +90,20 @@ genHandShakeMsg infoHash peer_id = concat [pstrlen, pstr, reserved, infoHash, pe 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 @@ -170,10 +174,8 @@ getMsg h = do 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))) @@ -252,7 +254,8 @@ updatePieceAvailability pieceStatus p pieceList = 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