Class: WebSocketRb::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/web_socket_rb/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(routes) ⇒ Server



9
10
11
12
13
# File 'lib/web_socket_rb/server.rb', line 9

def initialize(routes)
  @routes      = routes
  @connections = []
  @mutex       = Mutex.new
end

Instance Method Details

#runObject

Run each request in separate thread



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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