Last active
February 26, 2017 07:35
-
-
Save michalc/b1aa0df50c5b5a3da8f433e2c6fd7cae to your computer and use it in GitHub Desktop.
Simple echo server in Haskell that accepts multiple connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Network.Socket hiding (send, sendTo, recv, recvFrom) | |
import Network.Socket.ByteString | |
import Control.Concurrent | |
port = 4242 | |
incomingBufferSize = 4096 | |
main = do | |
-- Listen | |
sock <- socket AF_INET Stream 0 | |
setSocketOption sock ReuseAddr 1 | |
bind sock (SockAddrInet port iNADDR_ANY) | |
listen sock sOMAXCONN | |
mainLoop sock | |
mainLoop :: Socket -> IO () | |
mainLoop sock = do | |
-- Blocks until connection made | |
(conn, _) <- accept sock | |
forkIO (echoLoop conn) | |
mainLoop sock | |
echoLoop :: Socket -> IO () | |
echoLoop conn = do | |
incoming <- recv conn incomingBufferSize | |
send conn incoming | |
echoLoop conn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment