Last active
August 29, 2015 14:17
-
-
Save Sen/4b702fb242d6bc8b4b4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run | |
EventMachine::run { | |
Signal.trap("INT") { EventMachine.stop } | |
Signal.trap("TERM") { EventMachine.stop } | |
client = Faye::Client.new('http://tangpin.dev:6901/pulling') | |
store = Store.new | |
ws = WebSocket.new(client, store) | |
ws.subscribe | |
} | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Store | |
def initialize() | |
@redis = EM::Hiredis.connect("redis://localhost:6379/0") | |
end | |
def set_online_user(user_id, current_user_id) | |
k = key(current_user_id) | |
@redis.set(k, user_id).callback { | |
@redis.expire(k, 10) | |
} | |
end | |
def key(id) | |
"faye:online:user:#{id}" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WebSocket | |
def initialize(client, store) | |
@client = client | |
@store = store | |
end | |
def subscribe | |
@client.subscribe('/message_heartbeat') do |message| | |
user_id = message['user_id'] | |
current_user_id = message['current_user_id'] | |
case mark | |
when 'online' | |
if !user_id.nil? && !current_user_id.nil? | |
@store.set_online_user(user_id, current_user_id) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment