好的,这是本主题的延续:如何运行 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");
}
但是连接在客户端启动后立即关闭(连接已准备好,但未打开)。我期待别的东西...