class WebSocketRb::Server
Public Class Methods
new(routes)
click to toggle source
# File lib/web_socket_rb/server.rb, line 9 def initialize(routes) @routes = routes @connections = [] @mutex = Mutex.new end
Public Instance Methods
run()
click to toggle source
Run each request in separate thread
# File lib/web_socket_rb/server.rb, line 16 def run hostname = 'localhost' port = @routes.config.port || 9292 @socket = TCPServer.new(hostname, port) App.logger.info('Server') { "Started '#{hostname}' on port #{port}" } loop do Thread.start(@socket.accept) do |conn| @mutex.synchronize { @connections << conn } App.logger.info('Server') { 'New incoming connection' } begin Protocol::Handshake.new(conn).run @frames_sender = Service::FramesSender.new(@connections, conn) @sandbox = Context::Sandbox.new(@frames_sender) init_connection_code = @routes.init_connection_code @sandbox.instance_eval(&init_connection_code) if init_connection_code.is_a?(Proc) Protocol::FramesHandler.new(@connections, conn, @routes, @frames_sender, @sandbox).run rescue Error::HandshakeError => e e.messages(conn) rescue => e App.logger.error('Server') { e.message } ensure conn.close @mutex.synchronize { @connections.delete(conn) } close_block = @routes.close_connection_code @sandbox.instance_eval(&close_block) if close_block.is_a?(Proc) App.logger.info('Server') { 'Connection closed' } end end end end