-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkTest.hs
More file actions
57 lines (51 loc) · 1.61 KB
/
NetworkTest.hs
File metadata and controls
57 lines (51 loc) · 1.61 KB
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
import qualified Network as Net
import System.IO
import qualified System.IO.Error as IOErr
import System (getArgs)
import qualified Control.Concurrent as Conc
netWrite :: Handle -> String -> IO()
netWrite h s = do
hPutStr h s
hFlush h
handleConnection :: Handle -> String -> Net.PortNumber -> IO()
handleConnection h host portno = do
putStrLn "Ready for connection."
putStrLn ("Connection: " ++ host ++ " " ++ (show portno))
handleLines
putStrLn ("Closing connection: " ++ host ++ " " ++ (show portno))
hClose h
where
handleLines = do
v <- IOErr.try (hGetLine h)
case v of
Left _ -> putStrLn ("Error. ")
Right s -> do
putStrLn ("Input: " ++ s)
handleLines
doServer :: IO()
doServer = do
sock <- Net.listenOn (Net.PortNumber 6668)
handleConnections sock
where
handleConnections sock = do
(h, host, portno) <- Net.accept sock
_ <- Conc.forkIO $ handleConnection h host portno
handleConnections sock
doClient :: IO()
doClient = do
h <- Net.connectTo "localhost" (Net.PortNumber 6668)
s <- getLine
netWrite h s
hClose h
printUsage :: IO()
printUsage = do
putStrLn "Usage: NetworkTest [server|client]"
main :: IO()
main = Net.withSocketsDo $ do
cmdargs <- getArgs
case (length cmdargs) of
1 -> case (head cmdargs) of
"server" -> doServer
"client" -> doClient
_ -> printUsage
_ -> printUsage