Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby TCPServer sockets

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?

like image 684
Markus Orrelly Avatar asked Dec 13 '22 23:12

Markus Orrelly


1 Answers

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.

like image 76
Edu Avatar answered Jan 04 '23 04:01

Edu