WebSockets: How to notify all subscribers when a client connection has dropped?

557 views Asked by At

I have a little WebSocket chat demo that I am working on (based on this code). However, the part that doesn't seem to be working is when a connection is closed between a client and the server, I want to notify all the subscribers that the user has "left the chatroom". I thought that the server would be notified/run the onclose function when the client connection was dropped, but maybe that's not how WebSockets work.

Here's my EventMachine code:

  ws.onclose do
    puts "Connection closed"
    ws.send ({:type => 'status', :message => "#{@subscribers[subscriber_id]} has left the chatroom"}.to_json)
    @main_channel.unsubscribe(subscriber_id)
  end
1

There are 1 answers

0
tbuehlmann On BEST ANSWER

You are trying to send data to a WebSocket that was just closed, that won't work. You probably want to just push a message to the Queue like:

ws.onclose do
  puts "Connection closed"
  msg = {:type => 'status', :message => "#{@subscribers[subscriber_id]} has left the chatroom"}.to_json
  @main_channel.push(msg)
  @main_channel.unsubscribe(subscriber_id)
end

That way the message will be send to all subscribers.

Best regards

Tobias