I’m trying to get multiple clients to connect to a server. What I’ve managed to do is connect one client to a server by using for the server:
main = withSocketsDo $ do
socket <- listenOn port
(handle, host, portno) <- accept socket
hSetBuffering handle LineBuffering
msg <- hGetLine handle
putStrLn $ "The client says: " ++ msg
hClose handle
sClose socket
putStrLn "Server is done."
and for the client:
main = withSocketsDo $ do
handle <- connectTo "localhost" port
hSetBuffering handle LineBuffering
hPutStrLn handle "Hello!"
hClose handle
These are clearly just for testing purposes 😉
Now, I’ve read that I need to use forkIO to enable multiple clients to connect to this one server. However I haven’t been able to find how I should use forkIO or how to manage the several clients that will connect. Can someone explain to me what I should do?
Thanks in advance!
Just as a general style comment, I’d split the reaction of the server to the client’s connection into a separate function. This makes it easier to read in my opinion
now we probably want it to loop indefinitely, as that tends to be how most servers work. So we use forever (from Control.Monad)
and from here, the manner in which to use forkIO becomes quite clear