4

好的,这是本主题的延续:如何运行 Haskell WebSockets 库的官方示例。我想要一个服务器,它将在循环中响应每个客户端请求。

{-# LANGUAGE OverloadedStrings #-}

import Data.Char (isPunctuation, isSpace)
import Data.Monoid (mappend)
import Data.Text (Text)
import Control.Exception (fromException)
import Control.Monad (forM_, forever)
import Control.Concurrent (MVar, newMVar, modifyMVar_, readMVar)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Network.WebSockets

meow :: TextProtocol p => WebSockets p ()
meow = forever $ do
    msg <- receiveData
    sendTextData $ msg `T.append` ", meow."

app :: Request -> WebSockets Hybi00 ()
app _ = meow

main :: IO ()
main = runServer "0.0.0.0" 8000 app

现在我尝试从 JavaScript 中使用它:

var socket;  
var host = "ws://localhost:8000";  
var socket = new WebSocket(host);  
    console.log("ready");  
    socket.onopen = function(){  
         console.log("open");  
         socket.send("cats do ");
    }  
    socket.onmessage = function(msg){  
         console.log("msg");  
    }  
    socket.onclose = function(){  
         console.log("close");  
    }  

但是连接在客户端启动后立即关闭(连接已准备好,但未打开)。我期待别的东西...

4

1 回答 1

3

您需要先接受请求,然后才能开始使用 websocket 连接。例如

app :: Request -> WebSockets Hybi00 ()
app req = do
    acceptRequest req
    meow
于 2013-01-25T18:28:45.043 回答