2012-10-16 83 views
1

我正在嘗試使用EventMachine編寫聊天服務器。如何以線程安全的方式將消息從一個EventMachine連接傳遞給另一個?在EventMachine連接之間傳遞消息

我看到一個消息協議(Stomp)被支持,但我無法弄清楚如何使用它。任何幫助表示讚賞。

踐踏在EventMachine的 - http://eventmachine.rubyforge.org/EventMachine/Protocols/Stomp.html

+1

1. EM Stomp協議實現是一個客戶端,而不是服務器。 2. EM不必對Thread做任何事情(除非在某些特殊情況下使用'defer') –

回答

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 

UPDATE

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 
+0

邏輯發生在EventMachine :: Connection對象內部,所以我怎麼讓它們喚醒並檢查一個消息? – sparkymat

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 - 有一個很好的聊天室例子

相關問題