From: Bjorn Stahl Date: 2002-12-14T04:20:23+09:00 Subject: Re: TCP Server > > I just found an example in talk archive about using thread with tcp server. > > If anyone have a solution that does not use thread, please tell me, > > otherwise, please accept my apology that I should check the talk-archive > > first... :p > > I prefer to use select() than threads, for a couple reasons, in Ruby. > My sense is that, since the whole process is blocked (all your threads) > if one of your IO calls stalls (in any thread), then you have to find > a way to do non-blocking IO whether you're using threads or not. And I > personally find select() to be sufficient to the task without bothering > with threads. (It may just be personal opinion, or preference. :) I prefer to use a combination of both select and threads, I'm a bit thread-crazy though due to the extreme ease of thread-use in ruby :-) class SimpleTCPServer def initialize(port, interface, max_users = 4, timeout = 10) @server, @thread_limit = TCPServer.new(interface, port), max_users @thread_count = 0 @timeout = timeout end def handle_request( request ) # perform the actual request, return nil if the client should be closed end def handle_user( socket ) while not socket.closed? a = select([socket], nil, nil, @timeout) unless a == nil unless (b = handle_request( socket.readline.chop )) == nil socket.print b.to_s else socket.end end else socket.close end end end def listen while (session = server.accept) if (@thread_count < @thread_limit) Thread.new{ ref = session begin @thread_count += 1 handle_user( ref ) rescue IOError end ref.close unless ref.closed? @thread_count -= 1 } end end