849
|
1 |
module Miscutils where
|
|
2 |
|
|
3 |
import IO
|
|
4 |
import System.IO
|
|
5 |
import Control.Concurrent
|
|
6 |
import Control.Concurrent.STM
|
|
7 |
import Control.Exception (finally)
|
|
8 |
|
851
|
9 |
data ClientInfo =
|
|
10 |
ClientInfo
|
|
11 |
{
|
|
12 |
handle :: Handle,
|
|
13 |
nick :: String,
|
|
14 |
room :: String,
|
|
15 |
isMaster :: Bool
|
|
16 |
}
|
|
17 |
|
|
18 |
data RoomInfo =
|
|
19 |
RoomInfo
|
|
20 |
{
|
|
21 |
name :: String,
|
|
22 |
password :: String
|
|
23 |
}
|
|
24 |
|
|
25 |
|
849
|
26 |
sendMsg :: Handle -> String -> IO()
|
|
27 |
sendMsg clientHandle str = finally (return ()) (hPutStrLn clientHandle str >> hFlush clientHandle) -- catch exception when client tries to send to other
|
|
28 |
|
|
29 |
sendAll :: [Handle] -> String -> IO[()]
|
|
30 |
sendAll clientsList str = mapM (\x -> sendMsg x str) clientsList
|
|
31 |
|
|
32 |
sendOthers :: [Handle] -> Handle -> String -> IO[()]
|
|
33 |
sendOthers clientsList clientHandle str = sendAll (filter (/= clientHandle) clientsList) str
|
|
34 |
|
|
35 |
extractCmd :: String -> (String, [String])
|
|
36 |
extractCmd str = if ws == [] then ("", []) else (head ws, tail ws)
|
|
37 |
where ws = words str
|
|
38 |
|
|
39 |
manipState :: TVar[a] -> ([a] -> [a]) -> IO()
|
|
40 |
manipState state op =
|
|
41 |
atomically $ do
|
|
42 |
ls <- readTVar state
|
|
43 |
writeTVar state $ op ls
|
|
44 |
|
851
|
45 |
manipState2 :: TVar[ClientInfo] -> TVar[RoomInfo] -> ([ClientInfo] -> [RoomInfo] -> ([ClientInfo], [RoomInfo])) -> IO()
|
|
46 |
manipState2 state1 state2 op =
|
|
47 |
atomically $ do
|
|
48 |
ls1 <- readTVar state1
|
|
49 |
ls2 <- readTVar state2
|
|
50 |
let (ol1, ol2) = op ls1 ls2
|
|
51 |
writeTVar state1 ol1
|
|
52 |
writeTVar state2 ol2
|
|
53 |
|