]> git.rkrishnan.org Git - functorrent.git/commitdiff
read bytes off the handle and parse a message
authorRamakrishnan Muthukrishnan <ram@rkrishnan.org>
Wed, 6 May 2015 08:38:04 +0000 (14:08 +0530)
committerRamakrishnan Muthukrishnan <ram@rkrishnan.org>
Wed, 6 May 2015 08:38:04 +0000 (14:08 +0530)
src/FuncTorrent/Peer.hs

index c2268e894c94b3275a025f1742971745849f9dda..29d57143d814fb780a93f2a06c746667b8a266aa 100644 (file)
@@ -7,10 +7,11 @@ module FuncTorrent.Peer
 import Prelude hiding (lookup, concat, replicate, splitAt)
 
 import System.IO
 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 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)
 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
                            , 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.
 
 -- 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"
 
      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
 -- loop1 :: shake hands with all peers, find out the pieces they have, form PieceData.
 -- recvMsg :: Peer -> Handle -> Msg