jam-cloud/lib/jam_websockets/server.rb

81 lines
2.3 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]
connect_time_stale = options[:connect_time_stale].to_i
connect_time_expire = options[:connect_time_expire].to_i
@log.info "starting server #{host}:#{port} with staleness_time=#{connect_time_stale}; reconnect time = #{connect_time_expire}"
2012-10-23 03:16:14 +00:00
EventMachine.run do
@router.start(connect_time_stale)
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_expiration(connect_time_expire)
start_connection_flagger(connect_time_stale)
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_expiration(stale_max_time)
# one cleanup on startup
expire_stale_connections(stale_max_time)
EventMachine::PeriodicTimer.new(stale_max_time) do
expire_stale_connections(stale_max_time)
end
end
def expire_stale_connections(stale_max_time)
@log.debug("*** expire_stale_connections: fires each #{stale_max_time} seconds")
ConnectionManager.active_record_transaction do |connection_manager|
connection_manager.expire_stale_connections(stale_max_time)
2012-10-23 03:16:14 +00:00
end
end
def start_connection_flagger(flag_max_time)
# one cleanup on startup
flag_stale_connections(flag_max_time)
EventMachine::PeriodicTimer.new(flag_max_time) do
flag_stale_connections(flag_max_time)
end
end
def flag_stale_connections(flag_max_time)
@log.debug("*** flag_stale_connections: fires each #{flag_max_time} seconds")
ConnectionManager.active_record_transaction do |connection_manager|
connection_manager.flag_stale_connections(flag_max_time)
end
end
end
end