Class: ChainReactor::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/chain-reactor/server.rb

Overview

Creates a server socket and listens for client connections on an infinite loop. Each connecting client creates a new thread, allowing multiple connections at the same time.

Instance Method Summary collapse

Constructor Details

#initialize(address, port, reactor, logger) ⇒ Server

Create a new TCPServer listening on the given port.



13
14
15
16
17
18
# File 'lib/chain-reactor/server.rb', line 13

def initialize(address,port,reactor,logger)
  @server = TCPServer.open(address,port)
  @reactor = reactor
  @log = logger
  @log.info { "Started ChainReactor v#{VERSION} server on #{address}:#{port.to_s}" }
end

Instance Method Details

#start(multithreaded) ⇒ Object

Start the server listening on an infinite loop.

The multithreaded option allows each client connection to be opened in a new thread.

Keyboard interrupts are caught and handled gracefully.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/chain-reactor/server.rb', line 26

def start(multithreaded)
  if multithreaded
    Thread.abort_on_exception = true
    @log.info "Accepting concurrent connections with new threads"
  end
  begin
    loop do
      if multithreaded
        Thread.new(@server.accept) do |client_sock|
          handle_sock(client_sock)
        end
      else
        handle_sock(@server.accept)
      end
    end
  rescue Interrupt, SystemExit => e
    @server.close
    @log.info { "Shutting down the ChainReactor server" }
    raise e
  rescue Exception => e
    @server.close
    raise e
  end
end