与其他模块的套接字通信

时间:2016-02-06 08:25:26

标签: sockets haskell websocket server

我想运行一个websocket服务器并将消息从另一个模块发送给它。

到目前为止,我只设法将一个频道传递给启动服务器的模块。但是我希望像writeFile一样全球化,可以随时从任何模块调用。

此外,我希望拥有sendMessage的多个客户。一旦连接关闭,我认为该线程仍然停留在forever循环中。

Server.hs

import Network.WebSockets
import Control.Concurrent
import Control.Monad
import Data.ByteString

createServer :: IO (Chan ByteString)
createServer = do
    chan <- newChan
    forkIO $ runServer "127.0.0.1" 8080 (serverApp chan)
    ready <- readChan chan -- wait for client
    return chan

serverApp :: Chan ByteString -> PendingConnection -> IO ()
serverApp chan pending =
    do
        print "Client connected"
        connection <- acceptRequest pending
        writeChan chan "ready"
        forever $ do
            msg <- readChan chan
            sendTextData connection msg

sendMessage :: Chan ByteString -> ByteString -> IO ()
sendMessage = writeChan

Main.hs

main :: IO ()
main = do
    client <- createServer
    sendMessage client ("hello" :: ByteString)

1 个答案:

答案 0 :(得分:1)

我最终使用MVar unsafePerformIO。虽然不完全推荐,但代码简洁明了。

createServer :: IO ()
createServer = do
    _ <- forkIO $ runServer "127.0.0.1" 8080 serverApp
    return ()

serverApp :: PendingConnection -> IO ()
serverApp pending =
    do
        connection <- acceptRequest pending
        forever $ do
            msg <- takeMVar channel
            sendTextData connection msg

channel :: MVar ByteString
{-# NOINLINE channel #-}
channel = unsafePerformIO newEmptyMVar

sendMessage :: ByteString -> IO ()
sendMessage = putMVar channel

代码仍然缺少异常处理,它只适用于1个连接的客户端。