summaryrefslogtreecommitdiff
path: root/simplechat.hs
diff options
context:
space:
mode:
Diffstat (limited to 'simplechat.hs')
-rw-r--r--simplechat.hs66
1 files changed, 66 insertions, 0 deletions
diff --git a/simplechat.hs b/simplechat.hs
new file mode 100644
index 00000000..bf592db3
--- /dev/null
+++ b/simplechat.hs
@@ -0,0 +1,66 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE ScopedTypeVariables #-}
3
4import Data.HList.TypeEqGeneric1()
5import Data.HList.TypeCastGeneric1()
6import ByteStringOperators
7
8import Data.ByteString.Lazy.Char8 as L
9 ( ByteString
10 , hPutStrLn
11 , init )
12import System.IO
13 ( Handle
14 )
15import Control.Concurrent (forkIO)
16import Control.Concurrent.Chan
17import Data.HList
18
19import Server
20
21
22startCon socket st = do
23 let chan = hOccursFst st
24 nr = hOccursFst st :: ConnId
25 hdl = hOccursFst st :: Handle
26 quit = writeChan chan (nr,Nothing)
27 broadcast msg = writeChan chan (nr,Just msg)
28 chan' <- dupChan chan
29 reader <- forkIO $ fix $ \loop -> do
30 (nr', line) <- readChan chan'
31 case ( line, nr==nr') of
32 ( Nothing , True ) -> Prelude.putStrLn "quit-client."
33 ( Just msg , False ) -> hPutStrLn hdl msg >> loop
34 _ -> loop
35
36 hPutStrLn hdl "Hi, what's your name?"
37 line <- getPacket hdl
38 let name = L.init line
39 Prelude.putStrLn $ "readFst: " ++ show line
40 hPutStrLn hdl ("Welcome, " <++> name <++> "!")
41 broadcast ("--> " <++> name <++> " entered.")
42
43 return (name .*. ConnectionFinalizer quit .*. st)
44
45doCon st bs cont = do
46 let hdl = hOccursFst st :: Handle
47 nr = hOccursFst st :: ConnId
48 chan = hOccursFst st
49 broadcast msg = writeChan chan (nr,Just msg)
50 name = hHead st
51 Prelude.putStrLn $ "read: " ++ show bs
52 case bs of
53 "quit\n" -> hPutStrLn hdl "Bye!"
54 _ -> do
55 broadcast (name <++> ": " <++> L.init bs)
56 cont ()
57
58
59main = do
60 (chan :: Chan (ConnId, Maybe ByteString)) <- newChan
61 doServer (5222 .*. chan .*. HNil)
62 doCon
63 startCon
64 getLine
65
66