我正在尝试一个非常基本的服务器/客户端演示。我在客户端(浏览器中的用户)上使用 socket.io,在服务器上使用 eventmachine Echo 示例。理想情况下,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);
});
});
这是 ruby 代码:
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
最佳答案
您的客户端代码正在尝试使用 websockets 协议(protocol)连接到服务器。但是,您的服务器代码不接受 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
}
关于ruby - ruby 中的 socket.io 和 eventmachine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4897227/