Sha256: a5acef7ab331f731c630a7c80b5bd93954f56086481d83dc5a145de01155b64a

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

require 'socket'

module Backport
  module Server
    class Tcpip < Base
      include Connectable

      def initialize host: 'localhost', port: 1117, adapter: Adapter
        @socket = TCPServer.new(host, port)
        @adapter = adapter
        @stopped = false
      end

      def tick
        mutex.synchronize do
          clients.each do |client|
            if client.adapter.closed?
              client.stop
              next
            end
            input = client.read
            client.sending input unless input.nil?
          end
          clients.delete_if(&:stopped?)
        end
      end

      def starting
        start_accept_thread
      end

      def stopping
        super
        begin
          socket.shutdown
        rescue Errno::ENOTCONN, IOError
          # ignore
        end
        socket.close
      end

      def stopped?
        @stopped
      end

      private

      # @return [TCPSocket]
      attr_reader :socket

      def mutex
        @mutex ||= Mutex.new
      end

      def start_accept_thread
        Thread.new do
          until stopped?
            begin
              conn = socket.accept
              mutex.synchronize do
                addr = conn.addr(true)
                data = {
                  family: addr[0],
                  port: addr[1],
                  hostname: addr[2],
                  address: addr[3]
                }
                clients.push Client.new(conn, conn, @adapter, data)
                clients.last.run
              end
            rescue Exception => e
              STDERR.puts "Server stopped with exception [#{e.class}] #{e.message}"
              stop
              break
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
backport-0.2.0 lib/backport/server/tcpip.rb