Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io and eventmachine in ruby

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
like image 275
Amit Avatar asked Feb 04 '11 10:02

Amit


2 Answers

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
}
like image 139
eggie5 Avatar answered Sep 22 '22 18:09

eggie5


I'd look into using Cramp. It's an async framework with websockets support, built on top of EventMachine. I've played around with the samples and I have to admit that the API looks elegant and clean.

like image 24
John K. Chow Avatar answered Sep 22 '22 18:09

John K. Chow