Skip to content

Instantly share code, notes, and snippets.

@michalc
Created February 26, 2017 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalc/3c7132957c1541d4090abe1288934115 to your computer and use it in GitHub Desktop.
Save michalc/3c7132957c1541d4090abe1288934115 to your computer and use it in GitHub Desktop.
Simple delayed echo server in Haskell that accepts multiple connections
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import Control.Concurrent
port = 4242
incomingBufferSize = 4096
delayMicroseconds = 500000
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
threadDelay delayMicroseconds
send conn incoming
echoLoop conn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment