Eric Haase
4/15/2006 8:31:00 AM
Hello everyone,
I just started learning Ruby and I decided to mess around with
socket programming. However, I've encountered a problem and was
wondering if someone could help me out. I wrote a server and a client
program and the server is behaving strange when I invoke the
recv(bytes) method in the TCPSocket class. Here is my server code with
the error I'm receiving:
require 'socket'
abort "usage: #{__FILE__} [port]" if ARGV.size > 1
port = (ARGV[0] || 3434).to_i
server = TCPServer.new(port)
sockets = [server]
puts "listening on port ##{port}"
loop do
socketsReady = select(sockets)
next if socketsReady == nil
socketsReady[0].each do |socket|
if socket == server
client = socket.accept
sockets.push(client)
puts "established connection
(#{client.addr[-1]}:#{client.addr[1]})"
else
if socket.eof?
address = socket.addr
sockets.delete(socket)
socket.close
puts "closed connection (#{address[-1]}:#{address[1]})"
else
string = socket.recv(1024)
puts "received \"#{string}\"
(#{socket.addr[-1]}:#{socket.addr[1]})"
socket.puts(" server received your \"#{string}\"")
end
end
end
end
../server_bad.rb:27:in `recv': recv for buffered IO (IOError)
from ./server_bad.rb:27
from ./server_bad.rb:15
from ./server_bad.rb:12
The client code is as follows:
require 'socket'
abort "usage: #{__FILE__} [address] [port]" if ARGV.size != 2
socket = TCPSocket.new(ARGV[0],ARGV[1])
socket.send('hello',0)
socket.close
I can't seem to decipher the error code but one thing I did notice is
that when I use the same client code with the following server code
everything turns out fine:
require 'socket'
abort "usage: #{__FILE__} [port]" if ARGV.size != 1
server = TCPServer.new(ARGV[0].to_i)
socket = server.accept
puts "\"#{socket.recv(1024)}\""
socket.close
Anyone have any idea whats going on? The only relevant code that could
possibly cause the difference between the working server and the server
producing the error is the select method but I don't know why. If
someone can explain whats going on and how I could go about solving it
I would really appreciate it. Also, I've gotten them both to work with
'puts' and 'gets' but I don't want my system to retrieve bytes until a
newline. Any input would be appreciated. Thanks in advance for your
time!