I am developing a rails web page that should use the websocket functionality to communicate with an external ruby โโclient. To do this, I use the websocket-rails stone on the rails server, defining a client_connected client_disconnected event and a specific action to receive messages from the client (new_message).
On the client side, I tried using different ruby โโstones such as faye-websocket-ruby and websocket-client-simple , but I always get errors when I try to send a message. On the server, I cannot find a way to handle these messages. Both gems have a dispatch method that accepts only a string (not being able to specify the name of the event).
The code I used is as follows:
Server side
application / 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
configurations /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
configurations / 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| pe exit 1 end ws.on :error do |e| pe end hash = { channel: 'Example', message: 'Example' } ws.send 'new_message', hash loop do ws.send STDIN.gets.strip end
Faye-web socket
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. Best wishes.
PD: Let me know if you need more code.