patternMinor
Haskell network connection graceful handler
Viewed 0 times
haskellhandlernetworkconnectiongraceful
Problem
Just trying to work out some simple graceful connection handling code in Haskell to get my head around some of the IO/Networking/Threading stuff, some tips where I'm doing things poorly would be appreciated! I'm sure I could just use a module like network pipes that would handle all the graceful stuff for me out of the box, but this was just an exercise to try and understand basic network/multithreaded IO handling in haskell.
import Network
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import System.IO
type Connection = (Handle, HostName, PortNumber)
type ConnectionHandler = Connection -> IO ()
type Pool = [(ThreadId, Connection)]
main = runConn
fst' (a,b,c) = a
connFromPool (a,(b,c,d)) = b
runConn = withSocketsDo $ do
s > getLine
repeatAccept s p = do
c a -> IO ()
exitPool pool = \_ -> do
tid > hFlush h >> hClose h else return ()
atomically $ do
pool' > putChar x
repeatUntilExit :: Handle -> Handle -> (Char -> IO ()) -> [Char] -> IO ()
repeatUntilExit hIn hOut f "exit\n" = return ()
repeatUntilExit hIn hOut f x = do
c (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally action and_then =
mask $ \restore ->
forkIO $ try (restore action) >>= and_thenSolution
Just one remark: When handling
IO resources, I'd strongly suggest using bracket for resources that are obtained at some point and later released. Not only it makes your code much safer, it clearly demarcates which resource is used in which parts. And that also prevents separating opening and closing of resources, which is often a hard-to-find error.Context
StackExchange Code Review Q#23963, answer score: 2
Revisions (0)
No revisions yet.