Ruby TCPServer Sockets

I may have confused socket programming a bit, but should this not work?

srv = TCPServer.open(3333) client = srv.accept data = "" while (tmp = client.recv(10)) data += tmp end 

I tried almost any other method of "receiving" data from the TCPSocket client, but they all freeze and never exit the loop (getc, gets, read, etc.). I feel like I'm forgetting something. What am I missing?

+4
source share
3 answers

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

  • Know in advance the amount of data that will be transferred: in this case, you can use the read(size) method instead of recv(size) . read blocks until the total number of bytes is received.
  • You have a completion sequence: in this case, you save the loop to recv until you get a sequence of bytes indicating that the connection is complete.
  • After the connection is completed, the client closes the socket: in this case, read will return with partial data or with 0 and recv will return with data of size 0 data.empty?==true .
  • Define communication timeout: you can use the select function to get a timeout when no communication was made after a certain period of time. In this case, you close the socket and assume that all data has been transferred.

Hope this helps.

+8
source

Hmm, I keep doing this when the stack overflows [answering my own questions]. Maybe this will help someone else. I found an easier way to do 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 
+4
source

Nothing is written to the client.recv(10) so client.recv(10) returns nil or false. Try:
srv = TCPServer.open (3333) client = srv.accept

 data = "" while (tmp = client.recv(10) and tmp != 'QUIT') data += tmp end 
+1
source

Source: https://habr.com/ru/post/1303602/


All Articles