Class: Tarbit::Server

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeServer

Returns a new instance of Server.



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

def initialize
  @connections = []
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



18
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
# File 'lib/tarbit/server.rb', line 18

def run
  endpoint = Async::IO::Endpoint.parse("tcp://0.0.0.0:22")

  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 1
        if stream.eof?
          raise Async::TimeoutError.new
        end
        stream.write "#{rand(10)}\r\n"
      end
    rescue Async::TimeoutError => e
      @connections = @connections.reject { |stats| stats.fetch(:id) == id }
      Async.logger.info "Connection closed: #{stream}"
    end
  end
end