-
Notifications
You must be signed in to change notification settings - Fork 3
/
Client.hs
129 lines (111 loc) · 2.63 KB
/
Client.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
module Main where
import Control.Concurrent
import Control.Exception hiding (try)
import Control.Monad
import Message
import Network
import System.IO
import System.Console.Readline
import Text.ParserCombinators.Parsec
main = client "localhost" (PortNumber 9000)
client host port = withSocketsDo $ do
handle <- connectTo host port
hSetBuffering handle LineBuffering
hSetNewlineMode handle (NewlineMode CRLF CRLF)
forkIO $ (loop handle) `finally` (hClose handle)
(listener handle) `finally` (hClose handle)
loop handle = do
maybeCommand <- readline "% "
case maybeCommand of
Nothing -> return ()
Just "exit" -> return ()
Just command -> do
addHistory command
case parse parseCommand "input" command of
Left err -> do
putStrLn ("Error: " ++ show err)
loop handle
Right c -> do
hPutStrLn handle c
loop handle
listener handle = forever $ do
response <- hGetLine handle
case parse parseResponse "response" response of
Left err -> do
putStrLn ("Error: " ++ show err)
Right action -> do
action
parseCommand :: Parser String
parseCommand =
try parseLogin
<|> try parseJoin
<|> try parsePrivateMessage
<|> try parseRoomMessage
<|> try parsePart
<|> try parseLogout
<|> return "Couldn't parse"
parseLogin = do
string "/c "
name <- many (noneOf " ")
eof
return ("LOGIN " ++ name);
parseJoin = do
string "/j #"
room <- many (noneOf " ")
eof
return ("JOIN #" ++ room)
parseRoomMessage = do
string "/m #"
room <- many (noneOf " ")
char ' '
msg <- many anyChar
eof
return ("MSG #" ++ room ++ " " ++ msg)
parsePrivateMessage = do
string "/m "
to <- many (noneOf " ")
char ' '
msg <- many anyChar
eof
return ("MSG " ++ to ++ " " ++ msg)
parsePart = do
string "/p #"
room <- many (noneOf " ")
eof
return ("PART #" ++ room)
parseLogout = do
string "/q"
eof
return "LOGOUT"
parseResponse :: Parser (IO ())
parseResponse =
try parseOk
<|> try parseRoomMsg
<|> try parseUserMsg
<|> try parseError
<|> return (putStrLn "Unknown response from server")
parseOk = do
string "OK"
eof
return (return ())
parseRoomMsg = do
string "GOTROOMMSG "
user <- many (noneOf " ")
string " #"
room <- many (noneOf " ")
char ' '
msg <- many anyChar
eof
return (putStrLn ("#" ++ room ++ " " ++ user ++ ": " ++ msg))
parseUserMsg = do
string "GOTUSERMSG "
user <- many (noneOf " ")
char ' '
msg <- many anyChar
eof
return (putStrLn (user ++ ": " ++ msg))
parseError = do
string "ERROR "
reason <- many anyChar
eof
return (putStrLn ("ERROR " ++ reason))