Skip to content

Instantly share code, notes, and snippets.

@etozzato
Created August 12, 2010 19:25
Show Gist options
  • Save etozzato/521551 to your computer and use it in GitHub Desktop.
Save etozzato/521551 to your computer and use it in GitHub Desktop.
def start(&block)
raise ServerError, "already started." if @status != :Stop
server_type = @config[:ServerType] || SimpleServer
server_type.start{
@logger.info \
"#{self.class}#start: pid=#{$$} port=#{@listeners[0].addr[1]}"
call_callback(:StartCallback)
thgroup = ThreadGroup.new
@status = :Running
while @status == :Running
begin
if svrs = IO.select(@listeners, nil, nil, 2.0)
svrs[0].each{|svr|
@tokens.pop # blocks while no token is there.
if sock = accept_client(svr)
sock.do_not_reverse_lookup = config[:DoNotReverseLookup]
th = start_thread(sock, &block)
th[:WEBrickThread] = true
thgroup.add(th)
else
@tokens.push(nil)
end
}
end
rescue Errno::EBADF, IOError => ex
# if the listening socket was closed in GenericServer#shutdown,
# IO::select raise it.
rescue Exception => ex
msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
@logger.error msg
end
end
@logger.info "going to shutdown ..."
thgroup.list.each{|th| th.join if th[:WEBrickThread] }
call_callback(:StopCallback)
@logger.info "#{self.class}#start done."
@status = :Stop
}
end
def create_listeners(address, port, logger=nil)
unless port
raise ArgumentError, "must specify port"
end
res = Socket::getaddrinfo(address, port,
Socket::AF_UNSPEC, # address family
Socket::SOCK_STREAM, # socket type
0, # protocol
Socket::AI_PASSIVE) # flag
last_error = nil
sockets = []
res.each{|ai|
begin
while @socket.nil?
begin
@socket = TCPServer.new(ai[3], port)
port = @socket.addr[1] if port == 0
Utils::set_close_on_exec(@socket)
rescue Errno::EADDRINUSE
logger.warn("WEBRICK: port #{port} is already in use, trying #{port+1}")
port = 1 + port
end
end
sockets << @socket
rescue => ex
logger.warn("TCPServer Error: #{ex}") if logger
last_error = ex
end
}
raise last_error if sockets.empty?
return sockets
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment