2 # server.rb -- GenericServer Class
4 # Author: IPR -- Internet Programming with Ruby -- writers
5 # Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
6 # Copyright (c) 2002 Internet Programming with Ruby writers. All rights
9 # $IPR: server.rb,v 1.62 2003/07/22 19:20:43 gotoyuzo Exp $
14 require 'webrick/config'
19 class ServerError < StandardError; end
22 def SimpleServer.start
34 STDIN.reopen("/dev/null")
35 STDOUT.reopen("/dev/null", "w")
36 STDERR.reopen("/dev/null", "w")
42 attr_reader :status, :config, :logger, :tokens, :listeners
44 def initialize(config={}, default=Config::General)
45 @config = default.dup.update(config)
47 @config[:Logger] ||= Log::new
48 @logger = @config[:Logger]
50 @tokens = SizedQueue.new(@config[:MaxClients])
51 @config[:MaxClients].times{ @tokens.push(nil) }
53 webrickv = WEBrick::VERSION
54 rubyv = "#{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
55 @logger.info("WEBrick #{webrickv}")
56 @logger.info("ruby #{rubyv}")
59 unless @config[:DoNotListen]
61 warn(":Listen option is deprecated; use GenericServer#listen")
63 listen(@config[:BindAddress], @config[:Port])
64 if @config[:Port] == 0
65 @config[:Port] = @listeners[0].addr[1]
74 def listen(address, port)
75 @listeners += Utils::create_listeners(address, port, @logger)
79 raise ServerError, "already started." if @status != :Stop
80 server_type = @config[:ServerType] || SimpleServer
84 "#{self.class}#start: pid=#{$$} port=#{@config[:Port]}"
85 call_callback(:StartCallback)
87 thgroup = ThreadGroup.new
89 while @status == :Running
91 if svrs = IO.select(@listeners, nil, nil, 2.0)
93 @tokens.pop # blocks while no token is there.
94 if sock = accept_client(svr)
95 th = start_thread(sock, &block)
96 th[:WEBrickThread] = true
103 rescue Errno::EBADF, IOError => ex
104 # if the listening socket was closed in GenericServer#shutdown,
105 # IO::select raise it.
106 rescue Exception => ex
107 msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
112 @logger.info "going to shutdown ..."
113 thgroup.list.each{|th| th.join if th[:WEBrickThread] }
114 call_callback(:StopCallback)
115 @logger.info "#{self.class}#start done."
121 if @status == :Running
131 @logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
139 @logger.fatal "run() must be provided by user."
144 def accept_client(svr)
149 Utils::set_non_blocking(sock)
150 Utils::set_close_on_exec(sock)
151 rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPROTO => ex
152 # TCP connection was established but RST segment was sent
153 # from peer before calling TCPServer#accept.
154 rescue Exception => ex
155 msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
161 def start_thread(sock, &block)
164 Thread.current[:WEBrickSocket] = sock
167 @logger.debug "accept: #{addr[3]}:#{addr[1]}"
169 @logger.debug "accept: <address unknown>"
172 call_callback(:AcceptCallback, sock)
173 block ? block.call(sock) : run(sock)
174 rescue Errno::ENOTCONN
175 @logger.debug "Errno::ENOTCONN raised"
176 rescue ServerError => ex
177 msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
179 rescue Exception => ex
183 Thread.current[:WEBrickSocket] = nil
185 @logger.debug "close: #{addr[3]}:#{addr[1]}"
187 @logger.debug "close: <address unknown>"
194 def call_callback(callback_name, *args)
195 if cb = @config[callback_name]
199 end # end of GenericServer