Ruby websocket客户端用于websocket-rails gem

7
我正在开发一个Rails网页,需要使用WebSocket功能与外部Ruby客户端进行通信。为此,我在Rails服务器中使用websocket-rails gem,定义了client_connected、client_disconnected事件和接收来自客户端的消息(new_message)的特定动作。
在客户端上,我尝试使用不同的Ruby gems,如faye-websocket-ruby和websocket-client-simple,但是每当我尝试发送消息时,都会出现错误。在服务器上,我找不到处理这些消息的方法。这两个gems都有一个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

Client side

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' )
}

感谢您的提前帮助。此致敬礼。
附言:如果您需要更多代码,请告诉我。
1个回答

3

我终于找到了解决方法。问题在于消息需要按照特定格式构建,才能被websocket-rails理解。

例如:ws.send( '["new_message",{"data":"Example message"}]' )

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接