Chad Johnson
Chad Johnson

Reputation: 21905

Streaming socket service with EventMachine in Ruby not working

I have the following EventMachine-based Ruby client, but nothing outputs when it connects to the server:

EventMachine.run do
  conn = EventMachine::HttpRequest.new('http://localhost:10000')
  http = conn.get

  http.stream do |data|
    puts data  # THIS SHOULD BE OUTPUTTING SOMETHING
  end

  trap("INT")  { puts 'INT'; http.close; EventMachine.stop }
  trap("TERM") { puts 'TERM'; http.close; EventMachine.stop }
end

And the service:

module Simulation
  class QuoteService < EM::Connection
    def post_init
      puts "CONNECTION ESTABLISHED"  # THIS DOES OUTPUT

      EventMachine.add_periodic_timer(1) do
        puts "test data"  # THIS DOES OUTPUT
        send_data("test data")
      end
    end
  end
end

EventMachine.run do
  Signal.trap("INT")  { EventMachine.stop }
  Signal.trap("TERM") { EventMachine.stop }

  EventMachine.start_server('0.0.0.0', 10000, Simulation::QuoteService)
end

I think something is incorrect with the service. Any ideas why the client outputs nothing?

Upvotes: 0

Views: 252

Answers (1)

Casper
Casper

Reputation: 34338

Both your server and client work fine. Try and connect with the client to google.com:80 for example and you will see it works.

For the server just do telnet localhost 10000 and you will see here too that the server starts printing out test data.

But the problem is your server is not compatible with your client. Your client expects a HTTP server, but the server you're running is a simple EM::Connection that does not serve HTTP clients.

So when the client connects it expects a standard HTTP response, but all it gets is test data. So the stream part of the code will never get called.

You need to either run a HTTP server, or change the client to use EM::Connection instead of HttpRequest. I.e. both client and server need to talk the same protocol.

Upvotes: 2

Related Questions