--- /dev/null
+{-# LANGUAGE OverloadedStrings #-}
+module FuncTorrent.Server where
+
+import Control.Concurrent (forkIO)
+import Control.Monad (forever)
+import Network (withSocketsDo, listenOn, accept, Socket, PortID ( PortNumber ))
+import System.IO (hSetBuffering, BufferMode ( NoBuffering ))
+
+import FuncTorrent.Metainfo (Metainfo)
+import FuncTorrent.Peer (handlePeerMsgs, Peer(..))
+
+-- server is listening on any port from 6881 - 6889
+-- return the port number used
+start :: IO (Socket, PortID)
+start = withSocketsDo $ do
+ let portnums = [6881 .. 6889]
+ sock <- listenOn $ PortNumber $ fromIntegral (head portnums)
+ return (sock, PortNumber $ head portnums)
+
+run :: Socket -> String -> Metainfo -> IO ()
+run listenSock peerid m = forever $ do
+ (handle, ip, port) <- accept listenSock
+ let peer = Peer "" ip (fromIntegral port)
+ hSetBuffering handle NoBuffering
+ forkIO $ handlePeerMsgs peer peerid m
import Prelude hiding (log, length, readFile, getContents)
+import Control.Concurrent (forkIO)
import Data.ByteString.Char8 (ByteString, getContents, readFile, unpack)
import System.Environment (getArgs)
import System.Exit (exitSuccess)
import FuncTorrent.Logger (initLogger, logMessage, logStop)
import FuncTorrent.Metainfo (Info(..), Metainfo(..), torrentToMetainfo)
import FuncTorrent.Peer (handlePeerMsgs)
+import qualified FuncTorrent.Server as Server
import FuncTorrent.Tracker (peers, getTrackerResponse)
logError :: String -> (String -> IO ()) -> IO ()
Right m -> do
log "Input File OK"
log $ "Downloading file : " ++ name (info m)
- log "Trying to fetch peers"
+ log $ "starting server"
+ (serverSock, portnum) <- Server.start
+ log "Trying to fetch peers"
+ forkIO $ Server.run serverSock peerId m
log $ "Trackers: " ++ head (announceList m)
trackerResp <- getTrackerResponse peerId m
case trackerResp of