From: Eric Hodel Date: 2006-09-06T16:30:51+09:00 Subject: Re: Total newbie, but I think I found a bug in Socket? On Sep 5, 2006, at 8:00 PM, Patrick Toomey wrote: > Hello, > Fair warning...I'm extremely new to Ruby so please pardon any > ignorance on my part. > > Anyway, so the first thing I start to play around with after > reading through Programming Ruby is the socket library. Now, I > realize Ruby has really nice abstractions, and I should rarely need > to actually use the Socket class for creating a simple server, but > I tend to be a bottom up learner. So, I was attempting to run the > following code from the ruby-doc website: > > # In one script, start this first > require 'socket' > include Socket::Constants > socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) > sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) > socket.bind( sockaddr ) > socket.listen( 5 ) > client, client_sockaddr = socket.accept > puts "The client said, '#{socket.readline.chomp}'" > client.puts "Hello from script one!" > socket.close Here's the easiest way to create a simple server: require 'socket' server = TCPServer.new nil, 2200 client = server.accept puts "Client said: #{client.gets.chomp.inspect}" client.puts "Goodbye!" client.close server.close Here's one that handles multiple concurrent connections: require 'socket' server = TCPServer.new nil, 2200 loop do Thread.start server.accept do |client| message = client.gets.chomp puts "Client said: #{message.inspect}" client.puts "Goodbye client!" client.close exit if message == 'quit' end end -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com