websocket 在Rails中广播消息时未调用ActionCable通道

jhkqcmku  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(125)

首先,对ActionCable功能非常陌生。我一直在这里学习教程:https://www.driftingruby.com/episodes/push-notifications-with-actioncable
创建名为web_notifications_channel和web_notifications_channel.rb的通道:

class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "web_notifications_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

网络通知通道.js:

import consumer from "./consumer"

consumer.subscriptions.create("WebNotificationsChannel", {
  connected() {
    // Called when the subscription is ready for use on the server
  },

  disconnected() {
    // Called when the subscription has been terminated by the server
  },

  received(data) {
    // Called when there's incoming data on the websocket for this channel
    console.log(`wtf`)
    
  }
});

控制台中未显示任何内容。
已将cable.yml中的适配器设置更改为redis,以便从控制台请求:

development:
  adapter: redis

test:
  adapter: test

production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
  channel_prefix: community_rails_production

正在运行控制台命令:

ActionCable.server.broadcast 'web_notifications_channel', 'You have visited the welcome page.'

我得到的响应如下:

Broadcasting to web_notifications_channel: "You have visited the welcome page."
 => 0

但是我的received方法从来没有被调用过!!我在这里疯了,因为我不明白发生了什么!!我已经检查了一些类似的问题,但没有一个帮助我。
PS:我已经为Redis添加了宝石,并从我的控制台启动了Redis。

cbeh67ev

cbeh67ev1#

create方法的第一个参数是object,而不是string

consumer.subscriptions.create({ channel: "WebNotificationsChannel" }, {
  connected() {
    // Called when the subscription is ready for use on the server
  },

  disconnected() {
    // Called when the subscription has been terminated by the server
  },

  received(data) {
    // Called when there's incoming data on the websocket for this channel
    console.log(`wtf`)
    
  }
});

您还可以在devtool的Network选项卡中检查连接,通过WS进行过滤,以查看连接是否创建成功。
rails服务器或action cable服务器(如果您将action cable配置为作为独立服务器运行)也有日志,告诉您连接是成功还是失败,以及错误的详细信息(如果有)。

相关问题