在Ruby中使用WebSocket实现实时通讯可以借助于一些库,比如em-websocket
或者faye-websocket
。
下面是一个使用faye-websocket
库实现WebSocket实时通讯的示例:
faye-websocket
库:gem install faye-websocket
require 'faye/websocket'
require 'eventmachine'
EM.run {
class SimpleWebSocket
def call(env)
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env)
ws.on :message do |event|
ws.send(event.data)
end
ws.on :close do |event|
ws = nil
end
# Return async Rack response
ws.rack_response
else
[200, { 'Content-Type' => 'text/plain' }, ['Hello']]
end
end
end
# Run the WebSocket server
Rack::Handler::Thin.run SimpleWebSocket.new, Port: 3000
}
var ws = new WebSocket('ws://localhost:3000');
ws.onopen = function() {
console.log('WebSocket connection opened.');
ws.send('Hello, server!');
};
ws.onmessage = function(event) {
console.log('Received message from server: ' + event.data);
};
ws.onclose = function() {
console.log('WebSocket connection closed.');
};
通过以上步骤,您可以在Ruby中使用WebSocket轻松实现实时通讯。