Class: Tarbit::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/tarbit/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port = 22) ⇒ Server

Returns a new instance of Server.



14
15
16
17
# File 'lib/tarbit/server.rb', line 14

def initialize(port = 22)
  @connections = []
  @port = port.to_i
end

Instance Attribute Details

#connectionsObject (readonly)

Returns the value of attribute connections.



12
13
14
# File 'lib/tarbit/server.rb', line 12

def connections
  @connections
end

Instance Method Details

#runObject



19
20
21
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
47
48
49
50
51
52
53
# File 'lib/tarbit/server.rb', line 19

def run
  endpoint = Async::IO::Endpoint.parse("tcp://0.0.0.0:#{@port}")

  Async do |task|
    while true
      task.sleep 1
      Async.logger.info "Connection count: #{@connections.size}"
    end
  end

  Async do |task|
    endpoint.accept do |peer|
      stream = Async::IO::Stream.new(peer)
      Async.logger.info "New connection: #{stream}"

      id = SecureRandom.uuid

      @connections << {
          created_at: Date.new,
          id: id
      }

      while true do
        task.sleep 60
        if stream.eof? || stream.closed? || stream.io.closed?
          raise Async::TimeoutError.new
        end
        stream.write "#{rand(10)}\r\n"
      end
    rescue StandardError => e
      @connections = @connections.reject { |stats| stats.fetch(:id) == id }
      Async.logger.info "Connection closed: #{stream}"
    end
  end
end