websocketeventmachineem-websocket

em-websocket and javascript client connection


I've got a simple eventmachine web socket server (eventmachine 1.0.0):

EM.run {

  # WebSocket Server
  EM::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
    ws.onopen do
      sid = @channel.subscribe{|msg| ws.send msg }
      puts "* new WebSocket client <#{sid}> connected!"
    end

    ws.onmessage do |msg|
      puts "* websocket client <#{@sid}> : #{msg}"
    end

    ws.onclose do
      @channel.unsubscribe(sid)
      puts "* websocket client <#{@sid}> closed"
    end
  end
}

I'm trying to connect to it through a javascript client with the following code:

socket = new WebSocket("ws://localhost:8080");

socket.onopen = function(e) {
  socket.send('Connesso');
};

socket.onmessage = function(mess) {
  if (mess) {
    socket.send(mess);
  }
};

socket.onclose = function(e) {
  socket.send('Disconnesso');
};

With previous versions of safari it was working flawlessly with the latest one the client is not connecting to the server.

I tried it also with last Chrome Dev stable version but it's not working.

The web socket header is sent but it remains in pending status.

If I send a text message to the web socket I receive the INVALID_STATE_ERR: DOM Exception 11.

I saw that there has been a draft change but I thought em-websocket 0.3.8 already implemented it.

Can you help me solve this issue?

Thanks a lot


Solution

  • INVALID_STATE_ERR: DOM Exception 11 means your websocket is not in ready state yet.

    you can check state of websocket object by socket.readyState you are able to send messages when socket.readyState == 1

    I created a turnaround for this by using timeout

    timerId = setInterval(sendDataWhenReady, 1000);
    function sendDataWhenReady(){
      if(socket.readyState == 1){
        ws.send(JSON.stringify({"type": 'STATUS', "status": status, "username": logged_in_user}))
        clearInterval(timerId);
      }
    }