-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.hs
72 lines (63 loc) · 2.63 KB
/
Server.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module Server where
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Data.IORef
import Data.List
import System.IO
import Control.Concurrent
import System.Posix.Signals
import Protocol
import Rabin
import Control.Monad
main :: IO ()
main = do
withSocketsDo $ listn
reportSignal :: Socket -> ThreadId -> IORef Bool -> IO ()
reportSignal sock tid ref = do
putStrLn "\nShutting down."
killThread tid
sClose sock
writeIORef ref True
listn :: IO ()
listn = do
term <- newIORef False
sock <- socket AF_INET Stream 0
setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrInet 5555 iNADDR_ANY)
listen sock 2
tid <- forkIO $ serveloop sock
_ <- installHandler keyboardSignal (Catch $ reportSignal sock tid term) Nothing
waitloop term
waitloop :: IORef Bool -> IO ()
waitloop term = do
end <- readIORef term
if end
then return ()
else waitloop term
serveloop :: Socket -> IO ()
serveloop sock = do
conn <- accept sock
serveCon conn
serveloop sock
--The connection procedure is here
serveCon :: (Socket,SockAddr) -> IO ()
serveCon (sock,_) = do
(p,q) <- getKeys
sendKey sock (p*q)
--(Message msg) <- getFrame sock
--result <- processMsg p q msg
--putStr $ "Message received: " ++ result ++ "\n"
handleMsg sock p q
return ()
handleMsg :: Socket -> Integer -> Integer -> IO ()
handleMsg sock p q = do
first <- getFrame sock
case first of
(Message msg) -> do
result <- processMsg p q msg
putStr $ "Message received: " ++ result ++ "\n"
(Dossier count) -> do
frames <- replicateM (fromIntegral count) (getFrame sock)
msgs <- mapM (\(Message msg) -> processMsg p q msg) frames
let final = concat msgs
putStr $ "Message received: " ++ final ++ "\n"
_ -> error "Received the wrong packet!"