Skip to content

Instantly share code, notes, and snippets.

@aycanirican
Created October 21, 2014 05:55
Show Gist options
  • Save aycanirican/2e127b15eb4e61bcebca to your computer and use it in GitHub Desktop.
Save aycanirican/2e127b15eb4e61bcebca to your computer and use it in GitHub Desktop.
haskell udp example found in the wild
--
-- UDPEchoServer.hs: Exactly what the name says, a datagram echo server.
--
module Main (main) where
import Network.Socket
import System.Posix.Directory
import System.Posix.Files
import System.Posix.IO
import System.Posix.Process
import System.Exit
echoPort = 9900
maxline = 1500
--
-- The daemon infrastructure
--
main :: IO ()
main = do
pid <- forkProcess child
exitImmediately ExitSuccess
child :: IO ()
child = do
-- Set up the working directory, mask and standard i/o
-- for a daemon process (these will be inherited by
-- the forked process):
changeWorkingDirectory "/"
setFileCreationMask 0
mapM_ closeFd [stdInput, stdOutput, stdError]
nullFd <- openFd "/dev/null" ReadWrite Nothing
defaultFileFlags
mapM_ (dupTo nullFd) [stdInput, stdOutput, stdError]
closeFd nullFd
createSession -- This child becomes a process and session
-- group leader. This prevents the child of
-- this process (the daemon) from
-- ever getting a controlling terminal.
pid' <- forkProcess echoserver
exitImmediately ExitSuccess
--
-- The echo server daemon
--
echoserver :: IO ()
echoserver = do
withSocketsDo $ do
sock <- socket AF_INET Datagram 0
bindSocket sock (SockAddrInet echoPort iNADDR_ANY)
socketEcho sock
socketEcho :: Socket -> IO ()
socketEcho sock = do
(mesg, recv_count, client) <- recvFrom sock maxline
send_count <- sendTo sock mesg client
socketEcho sock
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment