0

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?

lucas clemente
  • 6,255
  • 8
  • 41
  • 61

1 Answers1

1

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_message call 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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • I see, that means I can't use any EM based websocket implementation. Are you aware of any that are not? – lucas clemente Nov 18 '12 at 22:30
  • 1
    What it means is you need to channel all of your socket operations through the main EventMachine thread. You can do this using `EM.next_tick` and pass it a block, for example. – tadman Nov 18 '12 at 23:22