Created
July 13, 2010 02:30
-
-
Save frsyuki/473373 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
require 'rubygems' | |
require 'rev/websocket' | |
class PubSub | |
def initialize | |
@subscriber = {} | |
@seqid = 0 | |
end | |
def subscribe(&block) | |
sid = @seqid += 1 | |
@subscriber[sid] = block | |
return sid | |
end | |
def unsubscribe(key) | |
@subscriber.delete(key) | |
end | |
def publish(data) | |
@subscriber.each_value {|block| | |
block.call(data) | |
} | |
end | |
end | |
$pubsub = PubSub.new | |
class MyConnection < Rev::WebSocket | |
def on_open | |
puts "WebSocket opened" | |
@sid = $pubsub.subscribe {|data| | |
send_message data | |
} | |
end | |
def on_message(data) | |
puts "WebSocket data received: '#{data}'" | |
$pubsub.publish(data) | |
end | |
def on_close | |
puts "WebSocket closed" | |
$pubsub.unsubscribe(@sid) | |
end | |
end | |
host = '0.0.0.0' | |
port = ARGV[0] || 8080 | |
server = Rev::WebSocketServer.new(host, port, MyConnection) | |
server.attach(Rev::Loop.default) | |
puts "start on #{host}:#{port}" | |
Rev::Loop.default.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment