Class: Proxi::Server

Inherits:
Object
  • Object
show all
Includes:
Wisper::Publisher
Defined in:
lib/proxi/server.rb

Overview

`Proxi::Server` accepts TCP requests, and forwards them, by creating an outbound connection and forwarding traffic in both directions.

The destination of the outbound connection, and the forwarding of data, is handled by a `Proxi::Connection`, created by a factory object, which can be a lambda.

Start listening for connections by calling #call.

`Proxi::Server` broadcasts the following events:

  • `new_connection(Proxi::Connection)`

  • `dead_connection(Proxi::Connection)`

Instance Method Summary collapse

Constructor Details

#initialize(listen_port, connection_factory, max_connections: 5) ⇒ Server

Public: Initialize a Server

listen_port - The String or Integer of the port to listen to for

incoming connections

connection_factory - Implements #call(in_socket) and returns a

Proxi::Connection

max_connections - The maximum amount of parallel connections to handle

at once

29
30
31
32
33
34
# File 'lib/proxi/server.rb', line 29

def initialize(listen_port, connection_factory, max_connections: 5)
  @listen_port = listen_port
  @connection_factory = connection_factory
  @max_connections = 5
  @connections = []
end

Instance Method Details

#callObject

Public: Start the server

Start accepting and forwarding requests


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/proxi/server.rb', line 39

def call
  @server = TCPServer.new('localhost', @listen_port)

  until @server.closed?
    in_socket = @server.accept
    connection = @connection_factory.call(in_socket)

    broadcast(:new_connection, connection)

    @connections.push(connection)

    connection.call # spawns a new thread that handles proxying

    reap_connections
    while @connections.size >= @max_connections
      sleep 1
      reap_connections
    end
  end
ensure
  close unless @server.closed?
end

#closeObject

Public: close the TCP server socket

Included for completeness, note that if the proxy server is active it will likely be blocking on TCPServer#accept, and the server port will stay open until it has accepted one final request.


67
68
69
# File 'lib/proxi/server.rb', line 67

def close
  @server.close
end