简单的Haskell WebSockets应用程序 - 连接在客户端启动后关闭(连接已准备好但未打开)

时间:2013-01-25 15:58:55

标签: haskell websocket

好的,这是本主题的延续:How to run official example of Haskell WebSockets library。我想要一个服务器,它将在循环中响应每个客户端请求。

{-# 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");  
    }  

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

1 个答案:

答案 0 :(得分:3)

在开始使用websocket连接之前,您需要accept the request。 E.g。

app :: Request -> WebSockets Hybi00 ()
app req = do
    acceptRequest req
    meow