jam-cloud/lib/jam_websockets/server.rb

62 lines
1.5 KiB
Ruby
Raw Normal View History

require 'em-websocket'
module JamWebsockets
2012-10-07 03:38:38 +00:00
class Server
def initialize(options={})
@log = Logging.logger[self]
@count=0
2012-10-23 03:16:14 +00:00
@router = Router.new
end
def run(options={})
host = "0.0.0.0"
port = options[:port]
max_stale_connection_time = options[:max_stale_connection_time]
@log.info "starting server #{host}:#{port} with staleness_time=#{max_stale_connection_time}"
2012-10-23 03:16:14 +00:00
EventMachine.run do
@router.start(max_stale_connection_time)
2012-10-23 03:16:14 +00:00
# if you don't do this, the app won't exit unless you kill -9
at_exit do
@log.info "cleaning up server"
@router.cleanup
end
start_connection_cleaner(max_stale_connection_time)
start_websocket_listener(host, port, options[:emwebsocket_debug])
end
end
def start_websocket_listener(listen_ip, port, emwebsocket_debug)
EventMachine::WebSocket.start(:host => listen_ip, :port => port, :debug => emwebsocket_debug) do |ws|
@log.info "new client #{ws}"
@router.new_client(ws)
end
end
def start_connection_cleaner(stale_max_time)
# one cleanup on startup
cleanup_stale_connections(stale_max_time)
EventMachine::PeriodicTimer.new(15) do
cleanup_stale_connections(stale_max_time)
end
end
def cleanup_stale_connections(stale_max_time)
ConnectionManager.active_record_transaction do |connection_manager|
connection_manager.remove_stale_connections(stale_max_time)
2012-10-23 03:16:14 +00:00
end
end
end
end