在EventMachine连接之间传递消息

时间:2012-10-16 07:12:49

标签: ruby eventmachine stomp

我正在尝试使用EventMachine编写聊天服务器。如何以线程安全的方式将消息从一个EventMachine连接传递到另一个?

我看到支持消息传递协议(Stomp),但我无法弄清楚如何使用它。任何帮助表示赞赏。

在EventMachine中踩踏 - http://eventmachine.rubyforge.org/EventMachine/Protocols/Stomp.html

2 个答案:

答案 0 :(得分:1)

请参阅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 - 有一个很好的聊天室示例

答案 1 :(得分:0)

尝试使用内存消息调度程序。

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