Class: OsCtld::Generic::Server

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

Overview

Generic socket server

A thread is spawned for every connected client. An instance of ClientHandler or its subclass is created to handle the connection.

Instance Method Summary collapse

Constructor Details

#initialize(socket, client_handler, opts = {}) ⇒ Server

Returns a new instance of Server

Parameters:

  • socket (BasicSocket)

    server socket

  • client_handler (Generic::ClientHandler)

    name of a class that will be instantiated for every client

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • opts (Hash)

    options passed to the client handler



14
15
16
17
18
# File 'lib/osctld/generic/server.rb', line 14

def initialize(socket, client_handler, opts = {})
  @socket = socket
  @client_handler = client_handler
  @opts = opts
end

Instance Method Details

#handle_client(socket) ⇒ Object (protected)



39
40
41
42
43
# File 'lib/osctld/generic/server.rb', line 39

def handle_client(socket)
  c = @client_handler.new(socket, @opts[:opts] || {})
  t = Thread.new { c.communicate }
  ThreadReaper.add(t, c)
end

#startObject



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/osctld/generic/server.rb', line 20

def start
  loop do
    begin
      c = @socket.accept

    rescue IOError
      return

    else
      handle_client(c)
    end
  end
end

#stopObject



34
35
36
# File 'lib/osctld/generic/server.rb', line 34

def stop
  @socket.close
end