ruby中的socket.io和eventmachine

Ami*_*mit 7 ruby sockets eventmachine socket.io

我正在尝试一个非常基本的服务器/客户端演示.我在客户端(浏览器中的用户)和服务器的eventmachine Echo示例中使用socket.io.理想情况下,socket.io应向服务器发送请求,服务器将打印接收的数据.不幸的是,事情并没有像我期望的那样发挥作用.

来源粘贴在这里:

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);
        });
    });
Run Code Online (Sandbox Code Playgroud)

这是红宝石代码:

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
Run Code Online (Sandbox Code Playgroud)

egg*_*ie5 9

您的客户端代码正在尝试使用websockets协议连接到服务器.但是,您的服务器代码不接受websockets连接 - 它只是在做HTTP.

一种选择是使用事件机器websockets插件:

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
}
Run Code Online (Sandbox Code Playgroud)