# Copyright (C) 2001 John W. Small All Rights Reserved
# Documentation:: Gavin Sinclair
# See the class GServer for documentation.
# GServer implements a generic server, featuring thread pool management,
# simple logging, and multi-server management. See HttpServer in
# <tt>xmlrpc/httpserver.rb</tt> in the Ruby standard library for an example of
# Any kind of application-level server can be implemented using this class.
# It accepts multiple simultaneous connections from clients, up to an optional
# maximum number. Several _services_ (i.e. one service per TCP port) can be
# run simultaneously, and stopped at any time through the class method
# <tt>GServer.stop(port)</tt>. All the threading issues are handled, saving
# you the effort. All events are optionally logged, but you can provide your
# own event handlers if you wish.
# Using GServer is simple. Below we implement a simple time server, run it,
# query it, and shut it down. Try this code in +irb+:
# # A server that returns the time in seconds since 1970.
# class TimeServer < GServer
# def initialize(port=10001, *args)
# # Run the server with logging enabled (it's a separate thread).
# server = TimeServer.new
# server.audit = true # Turn logging on.
# # *** Now point your browser to http://localhost:10001 to see it working ***
# # See if it's still running.
# GServer.in_service?(10001) # -> true
# server.stopped? # -> false
# # Shut the server down gracefully.
# # Alternatively, stop it immediately.
# # or, of course, "server.stop".
# All the business of accepting connections and exception handling is taken
# care of. All we have to do is implement the method that actually serves the
# As the example above shows, the way to use GServer is to subclass it to
# create a specific server, overriding the +serve+ method. You can override
# other methods as well if you wish, perhaps to collect statistics, or emit
# The above methods are only called if auditing is enabled.
# You can also override +log+ and +error+ if, for example, you wish to use a
# more sophisticated logging system.
DEFAULT_HOST = "127.0.0.1"
@@services = {} # Hash of opened ports, i.e. services
@@servicesMutex = Mutex.new
def GServer.stop(port, host = DEFAULT_HOST)
@@servicesMutex.synchronize {
@@services[host][port].stop
def GServer.in_service?(port, host = DEFAULT_HOST)
@@services.has_key?(host) and
@@services[host].has_key?(port)
@connectionsMutex.synchronize {
@tcpServerThread.raise "stop"
@tcpServerThread.join if @tcpServerThread
attr_reader :port, :host, :maxConnections
attr_accessor :stdlog, :audit, :debug
log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " +
"#{addr[2]}<#{addr[3]}> connect")
def disconnecting(clientPort)
log("#{self.class.to_s} #{@host}:#{@port} " +
"client:#{clientPort} disconnect")
protected :connecting, :disconnecting
log("#{self.class.to_s} #{@host}:#{@port} start")
log("#{self.class.to_s} #{@host}:#{@port} stop")
protected :starting, :stopping
log(detail.backtrace.join("\n"))
@stdlog.puts("[#{Time.new.ctime}] %s" % msg)
def initialize(port, host = DEFAULT_HOST, maxConnections = 4,
stdlog = $stderr, audit = false, debug = false)
@maxConnections = maxConnections
@connectionsMutex = Mutex.new
@connectionsCV = ConditionVariable.new
def start(maxConnections = -1)
raise "running" if !stopped?
@maxConnections = maxConnections if maxConnections > 0
@@servicesMutex.synchronize {
if GServer.in_service?(@port,@host)
raise "Port already in use: #{host}:#{@port}!"
@tcpServer = TCPServer.new(@host,@port)
@port = @tcpServer.addr[1]
@@services[@host] = {} unless @@services.has_key?(@host)
@@services[@host][@port] = self;
@tcpServerThread = Thread.new {
@connectionsMutex.synchronize {
while @connections.size >= @maxConnections
@connectionsCV.wait(@connectionsMutex)
client = @tcpServer.accept
@connections << Thread.new(client) { |myClient|
myPort = myClient.peeraddr[1]
serve(myClient) if !@audit or connecting(myClient)
@connectionsMutex.synchronize {
@connections.delete(Thread.current)
disconnecting(myPort) if @audit
@connectionsMutex.synchronize {
while @connections.size > 0
@connectionsCV.wait(@connectionsMutex)
@connections.each { |c| c.raise "stop" }
@@servicesMutex.synchronize {
@@services[@host].delete(@port)