author | koda |
Wed, 14 Oct 2009 22:12:02 +0000 | |
changeset 2443 | fececcbc2189 |
parent 2352 | 7eaf82cf0890 |
child 2867 | 9be6693c78cb |
permissions | -rw-r--r-- |
2348 | 1 |
{-# LANGUAGE ScopedTypeVariables #-} |
1804 | 2 |
module ClientIO where |
3 |
||
2296
19f2f76dc346
Patch for compiling with 6.10 (define NEW_EXCEPTIONS to do that)
unc0rr
parents:
2126
diff
changeset
|
4 |
import qualified Control.Exception as Exception |
1804 | 5 |
import Control.Concurrent.Chan |
6 |
import Control.Monad |
|
7 |
import System.IO |
|
8 |
---------------- |
|
9 |
import CoreTypes |
|
10 |
||
2001 | 11 |
listenLoop :: Handle -> Int -> [String] -> Chan CoreMessage -> Int -> IO () |
12 |
listenLoop handle linesNumber buf chan clientID = do |
|
1804 | 13 |
str <- hGetLine handle |
2001 | 14 |
if (linesNumber > 50) || (length str > 450) then |
15 |
writeChan chan $ ClientMessage (clientID, ["QUIT", "Protocol violation"]) |
|
1804 | 16 |
else |
2001 | 17 |
if str == "" then do |
18 |
writeChan chan $ ClientMessage (clientID, buf) |
|
19 |
listenLoop handle 0 [] chan clientID |
|
20 |
else |
|
21 |
listenLoop handle (linesNumber + 1) (buf ++ [str]) chan clientID |
|
1804 | 22 |
|
23 |
clientRecvLoop :: Handle -> Chan CoreMessage -> Int -> IO () |
|
24 |
clientRecvLoop handle chan clientID = |
|
2001 | 25 |
listenLoop handle 0 [] chan clientID |
2352 | 26 |
`catch` (\e -> clientOff (show e) >> return ()) |
1804 | 27 |
where clientOff msg = writeChan chan $ ClientMessage (clientID, ["QUIT", msg]) -- if the client disconnects, we perform as if it sent QUIT message |
28 |
||
29 |
clientSendLoop :: Handle -> Chan CoreMessage -> Chan [String] -> Int -> IO() |
|
30 |
clientSendLoop handle coreChan chan clientID = do |
|
31 |
answer <- readChan chan |
|
2296
19f2f76dc346
Patch for compiling with 6.10 (define NEW_EXCEPTIONS to do that)
unc0rr
parents:
2126
diff
changeset
|
32 |
doClose <- Exception.handle |
2348 | 33 |
(\(e :: Exception.IOException) -> if isQuit answer then return True else sendQuit e >> return False) $ do |
2352 | 34 |
forM_ answer (hPutStrLn handle) |
1804 | 35 |
hPutStrLn handle "" |
36 |
hFlush handle |
|
37 |
return $ isQuit answer |
|
38 |
||
39 |
if doClose then |
|
2348 | 40 |
Exception.handle (\(_ :: Exception.IOException) -> putStrLn "error on hClose") $ hClose handle |
1804 | 41 |
else |
42 |
clientSendLoop handle coreChan chan clientID |
|
43 |
||
44 |
where |
|
45 |
sendQuit e = writeChan coreChan $ ClientMessage (clientID, ["QUIT", show e]) |
|
2126 | 46 |
isQuit ("BYE":xs) = True |
47 |
isQuit _ = False |