Shouting server
concurrencyicon.icon
code:ShoutingServer.hs
module Main where
import Control.Concurrent (forkIO)
import Control.Monad (forever)
import Data.Char (toUpper)
import Network
import System.IO (Handle, hSetBuffering, BufferMode (LineBuffering),
hGetLine, hPutStrLn)
main :: IO ()
main = do
let port = PortNumber 8765
s <- listenOn port
putStrLn $ "listening on port " ++ show port
forever $ do
(h, host, p) <- accept s
putStrLn $ "client connected: " ++ host ++ ":" ++ show p
forkIO $ handleClient h --creates new thread
handleClient :: Handle -> IO ()
handleClient h = do
hSetBuffering h LineBuffering
forever $ do
line <- hGetLine h
hPutStrLn h $ map toUpper line
forkIO :: IO () -> IO ThreadId
Creates a new thread to run the IO computation passed as the first argument, and returns the ThreadId of the newly created thread.
When the buffer for the handle is not empty, the next item is obtained from the buffer; otherwise, when the buffer is empty, characters up to and including the next newline character are read into the buffer. No characters are available until the newline character is available or the buffer is full.
listenOn :: Port ID -> IO Socket
Creates the server side socket which has been bound to the specified port.
accept :: Socket -> IO (Handle, HostName, PortNumber)
Accept a connection on a socket created by listenOn.