Created
March 18, 2015 20:27
-
-
Save dtjm/cff1960fb47247c6bab7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
import System.IO | |
import Control.Monad | |
import Control.Monad.Fix (fix) | |
import Control.Concurrent | |
import Debug.Trace | |
import System.Log.Logger | |
import System.Log.Handler.Syslog | |
import System.Log.Handler.Simple | |
import Data.Conduit | |
import Data.Text | |
comp = "LoggingExample.Main" | |
trimSpace = unpack . strip . pack | |
main :: IO () | |
main = do | |
sh <- openlog "LoggingExample" [PID] LOCAL0 NOTICE | |
updateGlobalLogger comp $ addHandler sh | |
-- create socket | |
sock <- socket AF_INET Stream 0 | |
-- make socket immediately reusable - eases debugging. | |
setSocketOption sock ReuseAddr 1 | |
-- listen on TCP port 4242 | |
bindSocket sock (SockAddrInet 4242 iNADDR_ANY) | |
-- allow a maximum of 2 outstanding connections | |
listen sock 2 | |
mainLoop sock | |
mainLoop :: Socket -> IO () | |
mainLoop sock = do | |
-- accept one connection and handle it | |
conn <- accept sock | |
forkIO(runConn conn) | |
mainLoop sock | |
runConn :: (Socket, SockAddr) -> IO () | |
runConn (sock, _) = | |
let loop hdl buf = do | |
ineof <- hIsEOF hdl | |
case ineof of | |
True -> return () | |
_ -> do | |
line <- hGetLine hdl | |
let trimmedLine = trimSpace line | |
case trimmedLine of | |
"" -> do | |
traceIO buf | |
send sock buf | |
return () | |
_ -> loop hdl (buf ++ line ++ "\n") | |
in do | |
hdl <- socketToHandle sock ReadWriteMode | |
loop hdl "" | |
hClose hdl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment