Reputation: 7337
OK, this is continuation of this topic: How to run official example of Haskell WebSockets library. I want a server which will response to every client request in a loop.
{-# 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
Now I try to use it from 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");
}
But connection is closed just after client starts (connection is ready, but not opened). I expected something else...
Upvotes: 4
Views: 981
Reputation: 24802
You need to accept the request before you can start using the websocket connection. E.g.
app :: Request -> WebSockets Hybi00 ()
app req = do
acceptRequest req
meow
Upvotes: 3