【问题标题】:actioncable can't connect to websocketactioncable 无法连接到 websocket
【发布时间】:2026-01-25 11:05:01
【问题描述】:

我无法连接到 actioncable websocket。

我将此行添加到我的 routes.rb

match "/websocket", :to => ActionCable.server, via: [:get, :post]

我将此文件添加到我的应用程序路径中: 电缆/config.ru

# cable/config.ru
require ::File.expand_path('../../config/environment',  __FILE__)
Rails.application.eager_load!

require 'action_cable/process/logging'

run ActionCable.server

channels/application_cable/channel.rb

module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end

channels/application_cable/connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    protected
      def find_verified_user
        if current_user
          current_user
        else
          reject_unauthorized_connection
        end
      end
  end
end

和我的 javascriptfiles 下 assets/javascript/channels/index.coffee

#= require cable
#= require_self
#= require_tree .

@App = {}
# App.cable = Cable.createConsumer 'ws://localhost:28080'
# App.cable = Cable.createConsumer 'ws://localhost/websocket'

然后我启动了我的 rails 应用程序:

TRUSTED_IP=192.168.0.0/16 rails s -b 192.168.56.101 Puma

和我的 ActionCalbe-Server 与:

bundle exec puma -p 28080 cable/config.ru

当我在浏览器中打开我的应用程序时,出现以下错误:

Firefox kann keine Verbindung zu dem Server unter ws://localhost:28080/ aufbauen.
Firefox kann keine Verbindung zu dem Server unter ws://localhost/websocket aufbauen.

如何解决我的问题?我没有发现错误:/

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5 actioncable


    【解决方案1】:

    您的find_verified_user 方法毫无意义,它总是会失败。更改它以根据某些(签名)cookie 的存在来查找用户。

    def find_verified_user
      if user = User.find_by(id: cookies.signed[:user_id])
        user
      else
        reject_unauthorized_connection
      end
    end
    

    【讨论】:

      最近更新 更多