Module: ConnectionBase

Included in:
NotamConnector
Defined in:
src/connection_base.rb

Instance Method Summary collapse

Instance Method Details

#broadcast(event) ⇒ Object



18
19
20
# File 'src/connection_base.rb', line 18

def broadcast(event)
  puts event
end

#init(address, port, method) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'src/connection_base.rb', line 22

def init(address, port, method, &)
  endpoint = Async::IO::Endpoint.tcp(address, port)
  @server_tasks = []

  return init_connect(endpoint, &) if method == :connect

  # method :accept (Server)
  endpoint.each do |endpoint|
    server = endpoint.bind
    server.listen(Socket::SOMAXCONN)

    # bind to localhost instead of 0.0.0.0 and you'll get both IPv4 and IPv6
    LOGGER.info "Accepting connections from #{endpoint}..."
    @server_tasks << Async::Task.current.async do
      server.accept_each task: Async::Task.current do |socket, peer_addr, task: |
        init_core(socket, task, &)
        LOGGER.info :shutdown_server
      end
    ensure
      server.close
      broadcast :connection_closed_server
      close_signals
    end
  end
end

#init_connect(endpoint) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
# File 'src/connection_base.rb', line 59

def init_connect(endpoint, &)
  LOGGER.info "Try open connection to #{endpoint}"
  endpoint.connect do |socket, task|
    res = init_core(socket, task, &)
    LOGGER.info :shutdown_client
    res
  ensure
    socket.close
    broadcast :connection_closed_client
    # close_signals
  end
end

#init_core(socket, task, &block) ⇒ Object



72
73
74
75
76
77
78
79
# File 'src/connection_base.rb', line 72

def init_core(socket, task, &block)
  @current_stream = Async::IO::Stream.new socket
  block.call task
rescue EOFError
  LOGGER.info :connection_closed_by_peer
ensure
  @current_stream.close
end

#shutdownObject



48
49
50
51
52
53
54
55
56
57
# File 'src/connection_base.rb', line 48

def shutdown
  @current_stream&.close
  @waiting_data&.stop
  @server_tasks.each(&:stop)
  @shutdown = true

  # children = Async::Task.current.children
  # LOGGER.dubug :server_children, children
  # children.each(&:stop)
end