Class: AsyncTCPServer

Inherits:
AsyncEmitter
  • Object
show all
Defined in:
lib/async_tcpserver.rb

Overview

Asynchronous TCP Server implementation

Wraps TCPServer. The server emits, :connect to signal a new connection - a AsyncTCPSocket is passed to the Proc, :error to signal errors.

If the accept method is called with the argument false it is non-blocking, otherwise it blocks; the example below blocks on the gets call as an example of a non-blocking accept.

Example

require "./lib/async_tcpserver"

server = AsyncTCPServer.new 8000, 10

server.on :error, Proc.new { |error|
    STDERR.puts "Error: #{error}"
    server.close
}

server.on :connect, Proc.new { |client| 
    client.on :data, Proc.new { |data|
        client.puts data
    }
}

server.accept false

gets

server.close

Author:

  • Greg Martin

Instance Method Summary collapse

Constructor Details

#initialize(*hostname, port, num_threads) ⇒ AsyncTCPServer

constructor

Parameters:

  • hostname (String)

    optional host to bind to

  • port (FixedNum)

    port to bind to

  • num_threads (FixedNum)

    initial number of threads


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/async_tcpserver.rb', line 50

def initialize (*hostname, port, num_threads)
	super()

	@listen_thread = nil
	@pool = ReadyPool.new num_threads, lambda { |client| thread_procedure client }

	begin		
		if (hostname.length == 0)
			@server = TCPServer.new port
		else
			@server = TCPServer.new hostname[0], port
		end
	rescue Exception => e
		emit :error, e
	end

end

Instance Method Details

#accept(blocking = true) ⇒ Object

listen for connection requests

Parameters:

  • blocking (Boolean) (defaults to: true)

    optional if set to false accept is non-blocking


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/async_tcpserver.rb', line 74

def accept (blocking=true)
	if !blocking
		@listen_thread = Thread.new do
			loop do
				client = @server.accept
				@pool.start client
			end
		end
	else
		loop do
			client = @server.accept
			@pool.start client
		end
	end	
end

#closeObject

close server socket


93
94
95
96
97
98
# File 'lib/async_tcpserver.rb', line 93

def close
	@server.close
	if @listen_thread != nil
		Thread.kill @listen_thread
	end
end