Sha256: 7bbb37a45f02571721645016c9c08eaabd5c33ef75093295c3969f9d6e2de1e6

Contents?: true

Size: 1.16 KB

Versions: 6

Compression:

Stored size: 1.16 KB

Contents

require 'socket'

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

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

  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

  def shutdown
    @server.close
  end

  # @return [Integer]
  def connections_size
    @connections.size
  end

  def post_init
    # Override this method
  end

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

  def unbind
    # Override this method
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
procon_bypass_man-0.3.12 lib/procon_bypass_man/support/simple_tcp_server.rb
procon_bypass_man-0.3.11 lib/procon_bypass_man/support/simple_tcp_server.rb
procon_bypass_man-0.3.10 lib/procon_bypass_man/support/simple_tcp_server.rb
procon_bypass_man-0.3.9 lib/procon_bypass_man/support/simple_tcp_server.rb
procon_bypass_man-0.3.8.1 lib/procon_bypass_man/support/simple_tcp_server.rb
procon_bypass_man-0.3.8 lib/procon_bypass_man/support/simple_tcp_server.rb