Module: Revactor::TCP

Defined in:
lib/revactor/tcp.rb

Overview

The TCP module holds all Revactor functionality related to the Transmission Control Protocol, including drop-in replacements for Ruby TCP Sockets which can operate concurrently using Actors.

Defined Under Namespace

Classes: ConnectError, Listener, ReadError, ResolveError, Socket, WriteError

Constant Summary collapse

CONNECT_TIMEOUT =

Number of seconds to wait for a connection

10

Class Method Summary collapse

Class Method Details

.connect(host, port, options = {}) ⇒ Object

Connect to the specified host and port. Host may be a domain name or IP address. Accepts the following options:

:active - Controls how data is read from the socket.  See the
          documentation for Revactor::TCP::Socket#active=


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/revactor/tcp.rb', line 33

def self.connect(host, port, options = {})
  socket = Socket.connect host, port, options
  socket.attach Rev::Loop.default

  Actor.receive do |filter|
    filter.when(T[Object, socket]) do |message, _|
      case message
      when :tcp_connected
        return socket
      when :tcp_connect_failed
        raise ConnectError, "connection refused"
      when :tcp_resolve_failed
        raise ResolveError, "couldn't resolve #{host}"
      else raise "unexpected message for #{socket.inspect}: #{message}"
      end              
    end

    filter.after(CONNECT_TIMEOUT) do
      raise ConnectError, "connection timed out"
    end
  end
end

.listen(addr, port, options = {}) ⇒ Object

Listen on the specified address and port. Accepts the following options:

:active - Default active setting for new connections.  See the
          documentation Rev::TCP::Socket#active= for more info

:controller - The controlling actor, default Actor.current

:filter - An symbol/class or array of symbols/classes which implement 
          #encode and #decode methods to transform data sent and 
          received data respectively via Revactor::TCP::Socket.
          See the "Filters" section in the README for more information


68
69
70
# File 'lib/revactor/tcp.rb', line 68

def self.listen(addr, port, options = {})
  Listener.new(addr, port, options).attach(Rev::Loop.default).disable
end