开发者

Ruby TCPServer sockets

开发者 https://www.devze.com 2022-12-22 15:46 出处:网络
Maybe I\'ve gotten my sockets programming way mixed up, but shouldn\'t something like this work? srv = TCPServer.open(3333)

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 (tm开发者_开发问答p = 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?


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.


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


There is nothing that can be written to the socket so that 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号