[英]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: 为了使服务器写得很好,您需要:
read(size)
instead of recv(size)
. read(size)
方法而不是recv(size)
。 read
blocks until the total amount of bytes is received. read
块直到收到总字节数。 recv
until you receive a sequence of bytes indicating the communication is over. recv
上保持一个循环,直到你收到一个字节序列,表明通信结束。 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
。 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.