From: Robert Klemme Date: 2005-02-11T18:45:02+09:00 Subject: Re: network program "Jeff Davis" schrieb im Newsbeitrag news:420C371D.4060604@empires.org... > I am writing an application and my design is for a non blocking tcp > server. I have written non blocking network apps in C before. > > I am having trouble digging through the standard library. I have done > this before in C with no problems. Are there some basic wrappers for the > normal C functions and constants? I couldn't even find the F_SETFL > constant to change the socket descriptor to non blocking. The constants > seem to be all over the place (some in Socket, but I also need > File::NONBLOCK, which is named differently than O_NONBLOCK...). When > reading the documentation it's asking for a packed sockaddr to be passed > to connect. > > Is this really the simplest, ruby-like way to build a non-blocking > network app? It seems like this is harder and messier than C. It's also > hard to find the constants and functions even if they do exist. AFAIK Ruby uses nonblocking IO interenally. The easiest is typically to use threads to cope with multiple concurrent IO. Example require 'socket' port = (ARGV[0] || 80).to_i server = TCPServer.new('localhost', port) while (session = server.accept) Thread.new(session) do |sock| begin # use sock ensure sock.close end end end Alternatively you can set up a fixed number of threads that handle requests. require 'socket' require 'thread' queue = Queue.new threads = (1..10).map do Thread.new(queue) do |q| while ( sock = q.deq ) begin # use sock rescue Exception => e $stderr.puts e ensure sock.close end end end end port = (ARGV[0] || 80).to_i server = TCPServer.new('localhost', port) while (session = server.accept) queue.enq session end Kind regards robert