]> git.netwichtig.de Git - user/henk/code/haskell/birch.git/blob - src/Lib.hs
Completed first steps
[user/henk/code/haskell/birch.git] / src / Lib.hs
1 module Lib
2     ( runBirch
3     ) where
4
5 import           System.IO            -- base
6 import qualified Network.Socket as N  -- network
7
8 -- Toplevel program
9 runBirch :: String -> N.PortNumber -> String -> [String] -> IO ()
10 runBirch myServer myPort myNick myChannels = do
11     h <- connectTo myServer myPort
12     write h "NICK" myNick
13     write h "USER" (myNick ++ " 0 * :tutorial bot")
14 --    map (write h "JOIN") myChannels
15     write h "JOIN" (head myChannels)
16     listen h
17
18 -- Connect to a server given its name and port number
19 connectTo :: N.HostName -> N.PortNumber -> IO Handle
20 connectTo host port = do
21     addr : _ <- N.getAddrInfo Nothing (Just host) (Just (show port))
22     sock <- N.socket (N.addrFamily addr) (N.addrSocketType addr) (N.addrProtocol addr)
23     N.connect sock (N.addrAddress addr)
24     N.socketToHandle sock ReadWriteMode
25
26 -- Send a message to a handle
27 write :: Handle -> String -> String -> IO ()
28 write h cmd args = do
29     let msg = cmd ++ " " ++ args ++ "\r\n"
30     hPutStr h msg          -- Send message on the wire
31     putStr ("> " ++ msg)   -- Show sent message on the command line
32
33 -- Process each line from the server
34 listen :: Handle -> IO ()
35 listen h = forever $ do
36     line <- hGetLine h
37     putStrLn line
38   where
39     forever :: IO () -> IO ()
40     forever a = do a; forever a