【问题标题】:Ruby websocket client for websocket-rails gem用于 websocket-rails gem 的 Ruby websocket 客户端
【发布时间】:2015-02-03 09:51:35
【问题描述】:

我正在开发一个 Rails 网页,它需要使用 websocket 功能与外部 ruby​​ 客户端进行通信。为了做到这一点,我在 rails 服务器中使用了 websocket-rails gem,定义了 client_connected client_disconnected 事件和从客户端接收消息的特定操作 (new_message)。

在客户端,我尝试使用不同的 ruby​​ gem,例如 faye-websocket-rubywebsocket-client-simple,但是当我尝试使用时总是会出错发送消息。在服务器上,我找不到处理这些消息的方法。两个 gem 都有一个 send 方法,只接受一个字符串(不能指定事件的名称)

我一直在使用的代码如下:

服务器端

app/controllers/chat_controller.rb

class ChatController < WebsocketRails::BaseController
  def new_message
    puts ')'*40
  end

  def client_connected
    puts '-'*40
  end

  def client_disconnected
    puts '&'*40
  end
end

config/events.rb

WebsocketRails::EventMap.describe do
  subscribe :client_connected, :to => ChatController, :with_method => :client_connected

  subscribe :message, :to => ChatController, :with_method => :new_message

  subscribe :client_disconnected, :to => ChatController, :with_method => :client_disconnected
end

config/initializers/websocket_rails.rb

WebsocketRails.setup do |config|
  config.log_path = "#{Rails.root}/log/websocket_rails.log"
  config.log_internal_events = true
  config.synchronize = false
end

客户端

websocket-client-simple

require 'rubygems'
require 'websocket-client-simple'

ws = WebSocket::Client::Simple.connect 'ws://localhost:3000/websocket'

ws.on :message do |msg|
  puts msg.data
end

ws.on :new_message do
  hash = { channel: 'example' }
  ws.send hash
end

ws.on :close do |e|
  p e
  exit 1
end

ws.on :error do |e|
  p e
end

hash = { channel: 'Example', message: 'Example' }
ws.send 'new_message', hash

loop do
  ws.send STDIN.gets.strip
end

faye-websocket

require 'faye/websocket'
require 'eventmachine'

EM.run {
  ws = Faye::WebSocket::Client.new('ws://localhost:3000/websocket')

  ws.on :open do |event|
    p [:open]
  end

  ws.on :message do |event|
    p [:message, event.data]
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
  end

  ws.send( 'Example Text' )
}

提前致谢。问候。

PD:如果您需要更多代码,请告诉我。

【问题讨论】:

    标签: ruby-on-rails websocket ruby-on-rails-4.1


    【解决方案1】:

    我终于找到了解决方案。问题是消息需要使用certain format 构造才能被websocket-rails 理解。

    示例:ws.send('["new_message",{"data":"示例消息"}]')

    new_message 是 websocket-rails 正在监听的事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多