There are three parts in my Rails application:
- A part which listens for HTML5 web sockets (em-websocket)
- a piece of JavaScript which connects to them
- and a part which task is to connect to these sockets from inside of the same web application (em-websocket-client) (Yes, I am trying to do some IPC in Phusion Passenger environment)
JavaScript code connects fine and Web sockets server is happy with such a client, but when I connect from em-websocket-client
a strange thing is happening: onclose
handler is being called without calling onopen
, and moreover - it is called for a socket which had been opened by web browser, not em-websocket-client
.
The same em-websocket-client
code, when executed in separate Ruby script through command line, works as planned. Here is the sample of em-websocket-client
code:
require 'em-websocket-client'
class WebSocketsClient
def initialize
Thread.new do
log 'In a thread'
EventMachine.run do
log 'EM run'
@conn = EventMachine::WebSocketClient.connect("ws://localhost:5050?user_id=1&page_token=JYUTbfYDTTliglififi")
@conn.callback do
log 'Callback'
@conn.send_msg({ message_type: 'phone_call', user_id: 1, order_id: 1}.to_json)
@conn.close_connection
end
@conn.errback do |e|
log 'Errback'
puts "Got error: #{e}"
end
@conn.stream do |msg|
#log 'Stream'
#puts "<#{msg}>"
#if msg.data == 'done'
# @conn.close_connection
#end
end
@conn.disconnect do
puts 'gone'
EventMachine::stop_event_loop
end
end
end
end
def send_phone_call(order_id, user_id)
@conn.send_msg({ message_type: 'phone_call', user_id: user_id, order_id: order_id}.to_json)
end
def log(text)
puts "WebSocketsClient: #{text}\n"
end
end
WebSocketsClient.new
onclose
on server side is being callsd as soon as EventMachine::WebSocketClient.connect
is executed on client side. It doesn't even come to @conn.disconnect
call.
One more thing I can conjecture is that this behaviour is due to using same EventMachine
mechanism by server and client inside of same Rails application.