我正在尝试使用 EventMachine 编写聊天服务器。如何以线程安全的方式将消息从一个 EventMachine 连接传递到另一个?
我看到支持消息传递协议 (Stomp),但我不知道如何使用它。任何帮助表示赞赏。
EventMachine 中的 Stomp - http://eventmachine.rubyforge.org/EventMachine/Protocols/Stomp.html
我正在尝试使用 EventMachine 编写聊天服务器。如何以线程安全的方式将消息从一个 EventMachine 连接传递到另一个?
我看到支持消息传递协议 (Stomp),但我不知道如何使用它。任何帮助表示赞赏。
EventMachine 中的 Stomp - http://eventmachine.rubyforge.org/EventMachine/Protocols/Stomp.html
见http://eventmachine.rubyforge.org/EventMachine/Channel.html
您可以尝试以下几行:
require 'eventmachine'
class Chat < EventMachine::Connection
def initialize channel
@channel = channel
end
def post_init
send_data 'Hello'
@sid = @channel.subscribe do |msg|
send_data msg
end
end
def receive_data(msg)
@channel.push msg
end
def unbind
@channel.unsubscribe @sid
end
end
EM.run do
@channel = EventMachine::Channel.new
EventMachine.start_server '127.0.0.1', 8081, Chat, @channel
end
编辑:另请查看https://github.com/eventmachine/eventmachine/tree/master/examples/guides/getting_started - 有一个不错的聊天室示例
尝试从内存消息调度程序开始。
require 'thread'
class Room
def initialize
@users = []
end
def join(user)
@users << user
end
def leave(user)
@user.delete(user)
end
def broadcast(message)
@users.each do |user|
user.enqueue(message)
end
end
end
class User
def initialize
@mutex = Mutex.new
@queued_messages = []
end
def enqueue(message)
@mutex.synchronize do
@queued_message << message
end
end
def get_new_messages
@mutex.synchronize do
output = @queued_messages
@queued_messages = []
end
return output
end
end
更新
ROOM = Room.new
class Connection
def user_logged_in
# @user = ...
ROOM.join(@user)
end
def received_message(message)
ROOM.broadcast(message)
end
def receive_send_more_messages_request(req)
messages = @user.get_new_messages
# write messages
end
def connection_closed
ROOM.leave(@user)
end
end