From: Ramakrishnan Muthukrishnan Date: Wed, 6 May 2015 08:38:04 +0000 (+0530) Subject: read bytes off the handle and parse a message X-Git-Url: https://git.rkrishnan.org/pf/content/en/seg/about/htmlfontify-example.html?a=commitdiff_plain;h=8729f096fdd015825999db40d3077e95ecd0a370;p=functorrent.git read bytes off the handle and parse a message --- 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