我正在构建一个必须连接到 IRC 网络(打开套接字)并托管 Web 应用程序的应用程序。一些数据应该在 IRC 部分和 Http 部分之间共享。在 Haskell 中实现这种并发的最佳方法是什么?应该Control.Monad.STM
用这个来实现吗?这是 web 框架也应该支持的东西,还是可以在启动 Scotty 之前分叉?
问问题
127 次
1 回答
1
我发现以下作品非常棒。我最终使用了 STM.TQueue。
listen :: SSL.SSL -> IO ()
listen ssl = do
lines <- BL.lines `fmap` SSL.lazyRead ssl
mapM_ (processLine ssl . show) lines
processQueue :: SSL.SSL -> TQueue String -> IO ()
processQueue ssl queue = forever $ do newData <- atomically $ readTQueue queue
privmsg ssl newData
web_service :: TQueue String -> IO ()
web_service queue = scotty 25000 $ do
get "/" $ do
liftIO $ atomically $ writeTQueue queue "test passed"
status ok200
irc_bot :: [AddrInfo] -> TQueue String -> IO ()
irc_bot addrs queue = do ssl <- connectToServer (head addrs)
forkIO $ listen ssl
processQueue ssl queue
main = withOpenSSL $ do
let hints = defaultHints { addrSocketType = Stream, addrFamily = AF_INET }
addrs <- getAddrInfo (Just hints) (Just "irc.freenode.com") (Just "6697")
queue <- atomically newTQueue
forkIO $ irc_bot addrs queue
web_service queue
于 2015-03-18T18:08:47.460 回答