WebSockets:当客户端连接断开时如何通知所有订阅者?

发布于 2024-12-13 22:35:00 字数 518 浏览 0 评论 0原文

我正在制作一个小型 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽清梦 2024-12-20 22:35:00

您正在尝试将数据发送到刚刚关闭的 WebSocket,这是行不通的。您可能只想将消息推送到队列,如下所示:

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

这样消息将发送给所有订阅者。

最好的问候

托比亚斯

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文