WebSockets:当客户端连接断开时如何通知所有订阅者?
我正在制作一个小型 WebSocket 聊天演示(基于此代码)。然而,似乎不起作用的部分是当客户端和服务器之间的连接关闭时,我想通知所有订阅者用户已“离开聊天室”。我认为当客户端连接断开时,服务器会收到通知/运行 onclose 函数,但也许这不是 WebSocket 的工作方式。
这是我的 EventMachine 代码:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试将数据发送到刚刚关闭的 WebSocket,这是行不通的。您可能只想将消息推送到队列,如下所示:
这样消息将发送给所有订阅者。
最好的问候
托比亚斯
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:
That way the message will be send to all subscribers.
Best regards
Tobias