877
|
1 |
module Main where
|
|
2 |
|
|
3 |
import Network
|
|
4 |
import IO
|
|
5 |
import System.IO
|
|
6 |
import Control.Concurrent
|
|
7 |
import Control.Concurrent.STM
|
|
8 |
import Control.Exception (finally)
|
|
9 |
import Control.Monad (forM, filterM, liftM)
|
|
10 |
import Miscutils
|
|
11 |
|
889
|
12 |
acceptLoop :: Socket -> TChan ClientInfo -> IO ()
|
877
|
13 |
acceptLoop servSock acceptChan = do
|
|
14 |
(cHandle, host, port) <- accept servSock
|
|
15 |
cChan <- atomically newTChan
|
|
16 |
forkIO $ clientLoop cHandle cChan
|
889
|
17 |
atomically $ writeTChan acceptChan (ClientInfo cChan cHandle "" "" False)
|
877
|
18 |
acceptLoop servSock acceptChan
|
|
19 |
|
|
20 |
listenLoop :: Handle -> TChan String -> IO ()
|
|
21 |
listenLoop handle chan = do
|
|
22 |
str <- hGetLine handle
|
|
23 |
atomically $ writeTChan chan str
|
|
24 |
listenLoop handle chan
|
|
25 |
|
|
26 |
clientLoop :: Handle -> TChan String -> IO ()
|
|
27 |
clientLoop handle chan =
|
|
28 |
listenLoop handle chan
|
|
29 |
`catch` (const $ clientOff >> return ())
|
|
30 |
`finally` hClose handle
|
|
31 |
where clientOff = atomically $ writeTChan chan "QUIT"
|
|
32 |
|
889
|
33 |
mainLoop :: Socket -> TChan ClientInfo -> [ClientInfo] -> [RoomInfo] -> IO ()
|
|
34 |
mainLoop servSock acceptChan clients rooms = do
|
877
|
35 |
r <- atomically $ (Left `fmap` readTChan acceptChan) `orElse` (Right `fmap` tselect clients)
|
|
36 |
case r of
|
889
|
37 |
Left ci -> do
|
|
38 |
mainLoop servSock acceptChan (ci:clients) rooms
|
|
39 |
Right (line, clhandle) -> do
|
|
40 |
--handleCmd handle line
|
878
|
41 |
clients' <- forM clients $
|
889
|
42 |
\ci -> do
|
|
43 |
hPutStrLn (handle ci) line
|
|
44 |
hFlush (handle ci)
|
|
45 |
return [ci]
|
|
46 |
`catch` const (hClose (handle ci) >> return [])
|
|
47 |
mainLoop servSock acceptChan (concat clients') rooms
|
877
|
48 |
|
|
49 |
startServer serverSocket = do
|
|
50 |
acceptChan <- atomically newTChan
|
|
51 |
forkIO $ acceptLoop serverSocket acceptChan
|
889
|
52 |
mainLoop serverSocket acceptChan [] []
|
877
|
53 |
|
878
|
54 |
main = withSocketsDo $ do
|
877
|
55 |
serverSocket <- listenOn $ Service "hedgewars"
|
|
56 |
startServer serverSocket `finally` sClose serverSocket
|