Ruby websocket client for websocket-rails gem

怎甘沉沦 提交于 2019-12-07 05:37:18

问题


I am developing a rails webpage which need to use websocket functionality to communicate with an external ruby client. In order to do this, I am using the websocket-rails gem in the rails server, definning the client_connected client_disconnected event and a specific action to received the messages from the client (new_message).

On the client side I have tried to use different ruby gems like faye-websocket-ruby and websocket-client-simple but I always obtain errors when I try to send a message. On the server I can't find the way to process these messages. Both gems has a send method with only accepts a string (not being able to specify the name of the event)

The code that I have been using is the following:

Server side

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

Thanks in advance. Regards.

PD: Let me know if you need more code.


回答1:


Finally I have found the solution. The problem was that the message needs to be constructed with a certain format in order to be understood by websocket-rails.

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

where new_message is the event which websocket-rails is listening to.



来源:https://stackoverflow.com/questions/28295874/ruby-websocket-client-for-websocket-rails-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!