在Ruby中使用WebSocket實(shí)現(xiàn)實(shí)時(shí)通訊可以借助于一些庫,比如em-websocket
或者faye-websocket
。
下面是一個(gè)使用faye-websocket
庫實(shí)現(xiàn)WebSocket實(shí)時(shí)通訊的示例:
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輕松實(shí)現(xiàn)實(shí)時(shí)通訊。