无法连接到具有远程原点的操作电缆

Seb*_*nes 5 ruby-on-rails actioncable

我在Rails应用程序上设置了一个websocket,并且能够从同一台服务器上连接和接收数据.

我现在的方法是创建一个这样的套接字:

class UsersChannel < ApplicationCable::Channel
  def subscribed
    stream_from "users_1"
  end

  def unsubscribed

  end
end
Run Code Online (Sandbox Code Playgroud)

然后我用javascript打开连接

new WebSocket('wss://domain.com/cable/users_1');

然后我以这种格式从页面广播和发送JSON:

ActionCable.server.broadcast "users_1", {
      store: {
        name: store.name,
        address: {
          full_address: location.address,
          latitude: location.latitude,
          longitude: location.longitude
        }
    }
Run Code Online (Sandbox Code Playgroud)

当触发时我可以在我的控制台中看到它出现.我在JS中添加了这个频道:

App.cable.subscriptions.create "UsersChannel",
  received: (data) ->
    console.log data
Run Code Online (Sandbox Code Playgroud)

现在我们正在使用React Native构建应用程序,当我们将此代码添加到我们的应用程序时:

var ws = new WebSocket('wss://domain.com/cable/users_1');

ws.onmessage = (e) => {
  console.log(e.data);
};
Run Code Online (Sandbox Code Playgroud)

我们看到它ping,但是当我们触发广播时什么都没收到.我还将其添加到配置文件中:

  config.action_cable.url = 'wss://domain.com/cable'
  config.action_cable.disable_request_forgery_protection = true
Run Code Online (Sandbox Code Playgroud)

谁知道为什么会这样?

Zed*_*TuX 0

我终于知道如何解决我的问题了。

解决您的问题

首先,就您的情况而言,您错过了订阅频道的步骤。你必须有一个像这样的 WebSocket sendJSON :onopen

JSON.stringify({
  command: 'subscribe',
  identifier: JSON.stringify({
    channel: 'MyNotificationChannel',
    user_id: userId
  })
})
Run Code Online (Sandbox Code Playgroud)

这将触发MyNotificationChannelsubscribed方法传递user_id作为参数(params[:user_id])。

起源

然后是《起源》的问题,这是我的问题。

Rails 端的 WebSocket 打开失败,并显示以下消息:

Request origin not allowed: https://loc.mydom.com:28080
Run Code Online (Sandbox Code Playgroud)

我的应用程序正在https://loc.mydom.com:3000/上运行,并且我已经为侦听端口 28080 的电缆分离了运行服务器。无论如何,这里的要点是该消息显示不被接受的来源。

在环境文件(config/environments/development.rb)中你只需要添加ActionCable.server.config.allowed_request_origins

Rails.application.configure do
  # ...
  ActionCable.server.config.allowed_request_origins = [
    'https://loc.mydom.com:3000/', # My web front app
    'https://loc.mydom.com:28080'  # The phone app
  ]
  # ...
end
Run Code Online (Sandbox Code Playgroud)

此后,我的 WebSocket 将连接并且我正在接收更新。