Module: Polyphony::Net

Defined in:
lib/polyphony/net.rb

Overview

A more elegant networking API

Class Method Summary collapse

Class Method Details

.setup_alpn(context, protocols) ⇒ Object

Sets up ALPN negotiation for the given context. The ALPN handler for the context will select the first protocol from the list given by the client that appears in the list of given protocols, according to the specified order.

Parameters:

  • context (SSLContext)

    SSL context

  • protocols (Array)

    array of supported protocols



60
61
62
63
64
65
# File 'lib/polyphony/net.rb', line 60

def setup_alpn(context, protocols)
  context.alpn_protocols = protocols
  context.alpn_select_cb = lambda do |peer_protocols|
    (protocols & peer_protocols).first
  end
end

.tcp_connect(host, port, opts = {}) ⇒ TCPSocket, SSLSocket

Create a TCP connection to the given host and port, returning the new socket. If opts[:secure] is true, or if an SSL context is given in opts[:secure_context], a TLS handshake is performed, and an SSLSocket is returned.

Parameters:

  • host (String)

    hostname

  • port (Integer)

    port number

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

    options to use

Options Hash (opts):

  • :secure (boolean)

    use a default context as SSL context, return SSLSocket instance

  • :secure_context (OpenSSL::SSL::SSLContext)

    SSL context to use, return SSLSocket instance

Returns:

  • (TCPSocket, SSLSocket)

    connected socket



23
24
25
26
27
28
29
30
# File 'lib/polyphony/net.rb', line 23

def tcp_connect(host, port, opts = {})
  socket = TCPSocket.new(host, port)
  if opts[:secure_context] || opts[:secure]
    secure_socket(socket, opts[:secure_context], opts.merge(host: host))
  else
    socket
  end
end

.tcp_listen(host = nil, port = nil, opts = {}) ⇒ TCPServer, SSLServer

Creates a server socket for accepting incoming connection on the given host and port. If opts[:secure] is true, or if an SSL context is given in opts[:secure_context], a TLS handshake is performed, and an SSLSocket is returned.

Parameters:

  • host (String) (defaults to: nil)

    hostname

  • port (Integer) (defaults to: nil)

    port number

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

    connection options

Returns:

  • (TCPServer, SSLServer)

    listening socket



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/polyphony/net.rb', line 41

def tcp_listen(host = nil, port = nil, opts = {})
  host ||= '0.0.0.0'
  raise 'Port number not specified' unless port

  socket = listening_socket_from_options(host, port, opts)
  if opts[:secure_context] || opts[:secure]
    secure_server(socket, opts[:secure_context], opts)
  else
    socket
  end
end