I’m using the em-ws-client gem, although I think my question is more general than that. I’m trying to send data from outside the EventMachine receive block, but it takes a very long time (~20s) for the data to be sent:
require "em-ws-client"
m = Mutex.new
c = ConditionVariable.new
Thread.new do
EM.run do
@ws = EM::WebSocketClient.new("ws://echo.websocket.org")
@ws.onopen do
puts "connected"
m.synchronize { c.broadcast }
end
@ws.onmessage do |msg, binary|
puts msg
end
end
end
m.synchronize { c.wait(m) }
@ws.send_message "test"
sleep 100
When I put the @ws.send_message "test" directly into the onopen method it works just fine. I don’t understand why my version doesn’t work. I found this issue in EventMachine, but I’m not sure whether it’s related.
Why does it take so long, and how can I fix that?
EventMachine is strictly single threaded and sharing of sockets between threads is not recommended. What you might be seeing here is an issue with the main EventMachine thread being unaware that you’ve submitted a
send_messagecall and leaving it buffered for an extended period of time.I’d be very, very careful when using threads with EventMachine. I’ve seen it malfunction and crash if you hit thread timing or synchronization problems.