Class: Backport::Server::Tcpip
- 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
-
#accept ⇒ Client?
Accept an incoming connection using accept_nonblock.
-
#initialize(host: 'localhost', port: 1117, adapter: Adapter, socket_class: TCPServer) ⇒ Tcpip
constructor
A new instance of Tcpip.
- #starting ⇒ Object
- #stopping ⇒ Object
- #tick ⇒ Object
Methods included from Connectable
Methods inherited from Base
#start, #started?, #stop, #stopped?
Constructor Details
#initialize(host: 'localhost', port: 1117, adapter: Adapter, socket_class: TCPServer) ⇒ Tcpip
Returns a new instance of Tcpip.
11 12 13 14 15 |
# File 'lib/backport/server/tcpip.rb', line 11 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
#accept ⇒ Client?
Accept an incoming connection using accept_nonblock. Return the resulting Client if a connection was accepted or nil if no connections are pending.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/backport/server/tcpip.rb', line 51 def accept result = nil mutex.synchronize do begin conn = socket.accept_nonblock 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) clients.last.run result = clients.last rescue IO::WaitReadable, Errno::EAGAIN => e # ignore rescue Errno::ENOTSOCK, IOError => e Backport.logger.info "Server stopped with minor exception [#{e.class}] #{e.}" stop rescue Exception => e Backport.logger.warn "Server stopped with major exception [#{e.class}] #{e.}" stop end end result end |
#starting ⇒ Object
31 32 33 |
# File 'lib/backport/server/tcpip.rb', line 31 def starting start_accept_thread end |
#stopping ⇒ Object
35 36 37 38 39 40 41 42 43 44 |
# File 'lib/backport/server/tcpip.rb', line 35 def stopping super return if socket.closed? begin socket.shutdown Socket::SHUT_RDWR rescue Errno::ENOTCONN, IOError => e Backport.logger.info "Minor exception while stopping server [#{e.class}] #{e.}" end socket.close end |
#tick ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/backport/server/tcpip.rb', line 17 def tick mutex.synchronize do clients.each do |client| if client.adapter.closed? client.stop next end input = client.read client.sending input unless input.nil? end clients.delete_if(&:stopped?) end end |