简体   繁体   English

Ruby TCPServer套接字

[英]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). 我几乎尝试了从客户端TCPSocket“获取”数据的所有其他方法,但所有这些方法都挂起并且永远不会突破循环(getc,get,read等)。 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(size)方法而不是recv(size) read blocks until the total amount of bytes is received. read块直到收到总字节数。
  • 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. 有一个终止序列:在这种情况下,你在recv上保持一个循环,直到你收到一个字节序列,表明通信结束。
  • 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 . 让客户端在完成通信后关闭套接字:在这种情况下, read将返回部分数据或0, recv将返回0大小数据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. 定义通信超时:您可以使用函数select ,以便在一段时间后没有进行通信时获得超时。 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. 没有什么可以写入套接字,以便client.recv(10)返回nil或false。

Try: 尝试:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM