From 8729f096fdd015825999db40d3077e95ecd0a370 Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Wed, 6 May 2015 14:08:04 +0530 Subject: [PATCH] read bytes off the handle and parse a message --- src/FuncTorrent/Peer.hs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/FuncTorrent/Peer.hs b/src/FuncTorrent/Peer.hs index c2268e8..29d5714 100644 --- a/src/FuncTorrent/Peer.hs +++ b/src/FuncTorrent/Peer.hs @@ -7,10 +7,11 @@ module FuncTorrent.Peer import Prelude hiding (lookup, concat, replicate, splitAt) import System.IO -import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton) -import qualified Data.ByteString.Char8 as BC (replicate, pack) +import Data.ByteString (ByteString, pack, unpack, concat, hGet, hPut, singleton, append) +import Data.ByteString.Lazy (fromStrict) +import qualified Data.ByteString.Char8 as BC (replicate, pack, readInt) import Network (connectTo, PortID(..)) -import Data.Binary (Binary(..)) +import Data.Binary (Binary(..), decode) import Data.Binary.Put (putWord32be, putWord16be, putWord8) import Data.Binary.Get (getWord32be, getWord16be, getWord8) import Control.Monad (replicateM, liftM) @@ -24,7 +25,7 @@ data PeerState = PeerState { handle :: Handle , am_choking :: Bool , am_interested :: Bool , peer_choking :: Bool - , peer_interested :: Bool } + , peer_interested :: Bool} -- Maintain info on every piece and the current state of it. -- should probably be a TVar. @@ -132,5 +133,13 @@ instance Binary PeerMsg where 9 -> liftM (PortMsg . fromIntegral) getWord16be _ -> error "unknown message ID" +getMsg :: Handle -> IO PeerMsg +getMsg h = do + lBS <- hGet h 4 + let (Just (l, _)) = BC.readInt lBS + msg <- hGet h l + return $ decode $ fromStrict $ append lBS msg + + -- loop1 :: shake hands with all peers, find out the pieces they have, form PieceData. -- recvMsg :: Peer -> Handle -> Msg -- 2.37.2