2 # Copyright (C) 2001 John W. Small All Rights Reserved
4 # Author:: John W. Small
5 # Documentation:: Gavin Sinclair
8 # See the class GServer for documentation.
15 # GServer implements a generic server, featuring thread pool management,
16 # simple logging, and multi-server management. See HttpServer in
17 # <tt>xmlrpc/httpserver.rb</tt> in the Ruby standard library for an example of
20 # Any kind of application-level server can be implemented using this class.
21 # It accepts multiple simultaneous connections from clients, up to an optional
22 # maximum number. Several _services_ (i.e. one service per TCP port) can be
23 # run simultaneously, and stopped at any time through the class method
24 # <tt>GServer.stop(port)</tt>. All the threading issues are handled, saving
25 # you the effort. All events are optionally logged, but you can provide your
26 # own event handlers if you wish.
30 # Using GServer is simple. Below we implement a simple time server, run it,
31 # query it, and shut it down. Try this code in +irb+:
36 # # A server that returns the time in seconds since 1970.
38 # class TimeServer < GServer
39 # def initialize(port=10001, *args)
43 # io.puts(Time.now.to_i)
47 # # Run the server with logging enabled (it's a separate thread).
48 # server = TimeServer.new
49 # server.audit = true # Turn logging on.
52 # # *** Now point your browser to http://localhost:10001 to see it working ***
54 # # See if it's still running.
55 # GServer.in_service?(10001) # -> true
56 # server.stopped? # -> false
58 # # Shut the server down gracefully.
61 # # Alternatively, stop it immediately.
63 # # or, of course, "server.stop".
65 # All the business of accepting connections and exception handling is taken
66 # care of. All we have to do is implement the method that actually serves the
71 # As the example above shows, the way to use GServer is to subclass it to
72 # create a specific server, overriding the +serve+ method. You can override
73 # other methods as well if you wish, perhaps to collect statistics, or emit
74 # more detailed logging.
81 # The above methods are only called if auditing is enabled.
83 # You can also override +log+ and +error+ if, for example, you wish to use a
84 # more sophisticated logging system.
88 DEFAULT_HOST = "127.0.0.1"
93 @@services = {} # Hash of opened ports, i.e. services
94 @@servicesMutex = Mutex.new
96 def GServer.stop(port, host = DEFAULT_HOST)
97 @@servicesMutex.synchronize {
98 @@services[host][port].stop
102 def GServer.in_service?(port, host = DEFAULT_HOST)
103 @@services.has_key?(host) and
104 @@services[host].has_key?(port)
108 @connectionsMutex.synchronize {
110 @tcpServerThread.raise "stop"
116 @tcpServerThread == nil
128 @tcpServerThread.join if @tcpServerThread
131 attr_reader :port, :host, :maxConnections
132 attr_accessor :stdlog, :audit, :debug
134 def connecting(client)
135 addr = client.peeraddr
136 log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " +
137 "#{addr[2]}<#{addr[3]}> connect")
141 def disconnecting(clientPort)
142 log("#{self.class.to_s} #{@host}:#{@port} " +
143 "client:#{clientPort} disconnect")
146 protected :connecting, :disconnecting
149 log("#{self.class.to_s} #{@host}:#{@port} start")
153 log("#{self.class.to_s} #{@host}:#{@port} stop")
156 protected :starting, :stopping
159 log(detail.backtrace.join("\n"))
164 @stdlog.puts("[#{Time.new.ctime}] %s" % msg)
169 protected :error, :log
171 def initialize(port, host = DEFAULT_HOST, maxConnections = 4,
172 stdlog = $stderr, audit = false, debug = false)
173 @tcpServerThread = nil
176 @maxConnections = maxConnections
178 @connectionsMutex = Mutex.new
179 @connectionsCV = ConditionVariable.new
185 def start(maxConnections = -1)
186 raise "running" if !stopped?
188 @maxConnections = maxConnections if maxConnections > 0
189 @@servicesMutex.synchronize {
190 if GServer.in_service?(@port,@host)
191 raise "Port already in use: #{host}:#{@port}!"
193 @tcpServer = TCPServer.new(@host,@port)
194 @port = @tcpServer.addr[1]
195 @@services[@host] = {} unless @@services.has_key?(@host)
196 @@services[@host][@port] = self;
198 @tcpServerThread = Thread.new {
202 @connectionsMutex.synchronize {
203 while @connections.size >= @maxConnections
204 @connectionsCV.wait(@connectionsMutex)
207 client = @tcpServer.accept
208 @connections << Thread.new(client) { |myClient|
210 myPort = myClient.peeraddr[1]
211 serve(myClient) if !@audit or connecting(myClient)
213 error(detail) if @debug
219 @connectionsMutex.synchronize {
220 @connections.delete(Thread.current)
221 @connectionsCV.signal
223 disconnecting(myPort) if @audit
228 error(detail) if @debug
235 @connectionsMutex.synchronize {
236 while @connections.size > 0
237 @connectionsCV.wait(@connectionsMutex)
241 @connections.each { |c| c.raise "stop" }
243 @tcpServerThread = nil
244 @@servicesMutex.synchronize {
245 @@services[@host].delete(@port)