sockets

milaz89 2018-03-07 06:52:06.752616 UTC

1-- Creates socket using provided allocator and handles all exceptions using bracket function.
2initializeSocket :: IO Net.Socket -> (Net.Socket -> IO ()) -> IO ()
3initializeSocket before = bracket before (\c -> do
4 (Net.MkSocket cint family stype pron _) <- before
5 print $ "closing socket " ++ show cint ++ " family " ++ show family
6 Net.close c)
7
8-- | Create new UNIX socket for node 'NodeId', listen to it and use supplied
9-- handler to process incoming connections.
10listenUnixSocket :: SocketDirectory
11 -> NodeId
12 -> (Conversation -> IO Bool)
13 -> IO ()
14listenUnixSocket socketDirectory (NodeId nodeId) handler =
15 initializeSocket allocator acceptLoop
16 where
17 acceptLoop socket = acceptServerSock socket >>= handler >>= flip when (acceptLoop socket)
18 allocator :: IO Net.Socket
19 allocator = do
20 socket <- Net.socket Net.AF_UNIX Net.Stream Net.defaultProtocol
21 let socketPath = socketDirectory </> show nodeId <.> "sock"
22 Net.bind socket $ Net.SockAddrUnix socketPath
23 Net.listen socket 5
24 return socket