Class: SimpleTCPServer

Inherits:
Object
  • Object
show all
Defined in:
lib/procon_bypass_man/support/simple_tcp_server.rb

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ SimpleTCPServer

Returns a new instance of SimpleTCPServer.



4
5
6
7
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 4

def initialize(host, port)
  @host = host
  @port = port
end

Instance Method Details

#connections_sizeInteger

Returns:

  • (Integer)


48
49
50
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 48

def connections_size
  @connections.size
end

#post_initObject



52
53
54
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 52

def post_init
  # Override this method
end

#receive_data(socket, data) ⇒ Object



56
57
58
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 56

def receive_data(socket, data)
  # Override this method
end

#runObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 14

def run
  loop do
    timeout = 5 # 5秒のタイムアウト
    readable, _ = IO.select(@connections + [@server], nil, nil, timeout)
    next if readable.nil? # timeoutを迎えるとnilになる

    readable.each do |socket|
      if socket == @server
        client = @server.accept
        post_init
        @connections << client
      else
        data = socket.gets
        if data.nil?
          @connections.delete(socket)
          unbind
          socket.close
        else
          receive_data(socket, data)
        end
      end
    end
  rescue Errno::EBADF, IOError => e
    unbind
    @connections = []
    @server.close
  end
end

#shutdownObject



43
44
45
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 43

def shutdown
  @server.close
end

#start_serverObject



9
10
11
12
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 9

def start_server
  @connections = []
  @server = TCPServer.new(@host, @port)
end

#unbindObject



60
61
62
# File 'lib/procon_bypass_man/support/simple_tcp_server.rb', line 60

def unbind
  # Override this method
end