socket.io and eventmachine in ruby

Amit picture Amit · Feb 4, 2011 · Viewed 8.4k times · Source

I am trying out a very basic server/client demo. I am using socket.io on the client(a user in a browser) and eventmachine Echo example for server. Ideally socket.io should send a request to server and server will print the received data. Unfortunately, something is not working as I expect it to.

Source is pasted here:

socket = new io.Socket('localhost',{
        port: 8080
    });
    socket.connect();
    $(function(){
        var textBox = $('.chat');
        textBox.parent().submit(function(){
            if(textBox.val() != "") {
                //send message to chat server
                socket.send(textBox.val());
                textBox.val('');
                return false;
            }
        });
        socket.on('message', function(data){
            console.log(data);
            $('#text').append(data);
        });
    });

and here is ruby code:

require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
class Echo < EM::Connection
  def receive_data(data)
    send_data(data)
  end
end

EM.run do
  EM.start_server '0.0.0.0', 8080, Echo
end

Answer

eggie5 picture eggie5 · Apr 19, 2011

You client code is trying to connect to a server using the websockets protocol. However, your server code isn't accepting websockets connections - it's only doing HTTP.

One option is to use the event machine websockets plugin:

https://github.com/igrigorik/em-websocket

EventMachine.run {

    EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
        ws.onopen {
          puts "WebSocket connection open"

          # publish message to the client
          ws.send "Hello Client"
        }

        ws.onclose { puts "Connection closed" }
        ws.onmessage { |msg|
          puts "Recieved message: #{msg}"
          ws.send "Pong: #{msg}"
        }
    end
}