Class: Backport::Server::Tcpip

Inherits:
Base
  • Object
show all
Includes:
Connectable
Defined in:
lib/backport/server/tcpip.rb

Overview

A Backport TCP server. It runs a thread to accept incoming connections and automatically stops when the socket is closed.

Instance Method Summary collapse

Methods included from Connectable

#clients

Methods inherited from Base

#start, #started?, #stop, #stopped?, #tick

Constructor Details

#initialize(host: 'localhost', port: 1117, adapter: Adapter, socket_class: TCPServer) ⇒ Tcpip

Returns a new instance of Tcpip.

Parameters:

  • host (String) (defaults to: 'localhost')
  • port (Integer) (defaults to: 1117)
  • adapter (Module, Class) (defaults to: Adapter)
  • socket_class (Class) (defaults to: TCPServer)


15
16
17
18
19
# File 'lib/backport/server/tcpip.rb', line 15

def initialize host: 'localhost', port: 1117, adapter: Adapter, socket_class: TCPServer
  @socket = socket_class.new(host, port)
  @adapter = adapter
  @stopped = false
end

Instance Method Details

#acceptClient?

Accept an incoming connection using accept_nonblock. Return the resulting Client if a connection was accepted or nil if no connections are pending.

Returns:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/backport/server/tcpip.rb', line 41

def accept
  result = nil
  mutex.synchronize do
    begin
      conn = socket.accept
      addr = conn.addr(true)
      data = {
        family: addr[0],
        port: addr[1],
        hostname: addr[2],
        address: addr[3]
      }
      clients.push Client.new(conn, conn, @adapter, data)
      this = self
      clients.last.adapter._data[:on_close] = Proc.new {
        conn.close
        changed
        notify_observers this
      }
      clients.last.add_observer self
      clients.last.run
      result = clients.last
    rescue IO::WaitReadable, Errno::EAGAIN
      # ignore
    rescue Errno::ENOTSOCK, IOError => e
      Backport.logger.info "Server stopped with minor exception [#{e.class}] #{e.message}"
      stop
    rescue StandardError => e
      Backport.logger.warn "Server stopped with major exception [#{e.class}] #{e.message}"
      stop
    end
  end
  result
end

#startingObject



21
22
23
# File 'lib/backport/server/tcpip.rb', line 21

def starting
  start_accept_thread
end

#stoppingObject



25
26
27
28
29
30
31
32
33
34
# File 'lib/backport/server/tcpip.rb', line 25

def stopping
  super
  return if socket.closed?
  begin
    socket.shutdown Socket::SHUT_RDWR
  rescue Errno::ENOTCONN, IOError => err
    Backport.logger.info "Minor exception while stopping server [#{err.class}] #{err.message}"
  end
  socket.close
end

#update(client) ⇒ void

This method returns an undefined value.

Parameters:



78
79
80
81
82
83
84
# File 'lib/backport/server/tcpip.rb', line 78

def update client
  if client.stopped?
    clients.delete client
  else
    client.tick
  end
end