views:

385

answers:

3

Maybe I've gotten my sockets programming way mixed up, but shouldn't something like this work?

srv = TCPServer.open(3333)
client = srv.accept

data = ""
while (tmp = client.recv(10))
    data += tmp
end

I've tried pretty much every other method of "getting" data from the client TCPSocket, but all of them hang and never break out of the loop (getc, gets, read, etc). I feel like I'm forgetting something. What am I missing?

+2  A: 

Hmm, I keep doing this on stack overflow [answering my own questions]. Maybe it will help somebody else. I found an easier way to go about doing what I was trying to do:

srv = TCPServer.open(3333)
client = srv.accept

data = ""
recv_length = 56
while (tmp = client.recv(recv_length))
    data += tmp
    break if tmp.length < recv_length
end
Markus Orrelly
the last chunk in the sequence you wish to send might be exactly `recv_length` in size and the loop will run once more (error).
clyfe
A: 

There is nothing that ca be written to the socket so that client.recv(10) to return nil or false. Try:
srv = TCPServer.open(3333) client = srv.accept

data = ""
while (tmp = client.recv(10) and tmp != 'QUIT')
    data += tmp
end
clyfe
+3  A: 

In order for the server to be well written you will need to either:

  • Know in advance the amount of data that will be communicated: In this case you can use the method read(size) instead of recv(size). read blocks until the total amount of bytes is received.
  • Have a termination sequence: In this case you keep a loop on recv until you receive a sequence of bytes indicating the communication is over.
  • Have the client closing the socket after finishing the communication: In this case read will return with partial data or with 0 and recv will return with 0 size data data.empty?==true.
  • Defining a communication timeout: You can use the function select in order to get a timeout when no communication was done after a certain period of time. In which case you will close the socket and assume every data was communicated.

Hope this helps.

Edu