Ruby TCPServer sockets

Markus Orrelly picture Markus Orrelly · Mar 9, 2010 · Viewed 7.2k times · Source

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?

Answer

Edu picture Edu · Mar 10, 2010

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.