简体   繁体   English

Python套接字导致挂起

[英]Python socket causing hang

Occasionally my python App hangs when there is a burst of send/receive on the socket.有时,当套接字上有突发的发送/接收时,我的 python 应用程序会挂起。 What am I missing here: seems basic:我在这里缺少什么:似乎很基本:

skt.send(packet)

and

skt.recv_into(pkt)

If a put a sleep(0.2) after the call, then it works fine.如果在调用后放置 sleep(0.2) ,则它可以正常工作。

Should I change to the select() way of talking to socket?我应该改用 select() 与 socket 对话的方式吗? I have tried 2.7 to 3.3 which seems to be better, but still that hang occurs.我尝试了 2.7 到 3.3,这似乎更好,但仍然发生挂起。

The socket is setup as:套接字设置为:

skt = socket(AF_INET, SOCK_STREAM)

skt.connect((ipAddress, nwPort))

There is far too little information to tell.要说的信息太少了。 I don't think there's a hang, but a sleep pending data (which you could disable with MSG_DONTWAIT or setblocking , or another check such as select) when you read, because data isn't present yet.我不认为有挂起,但是在您阅读时会出现睡眠挂起数据(您可以使用 MSG_DONTWAIT 或setblocking或其他检查(例如 select)禁用该数据),因为数据尚不存在。 If you know it has been sent, it's possible it's in various network delays, particularly Nagle's algorithm which you can disable with TCP_NODELAY.如果您知道它已发送,则可能存在各种网络延迟,尤其是Nagle 的算法,您可以使用 TCP_NODELAY 禁用该算法 You should generally use select or poll if you want your program to be responsive - note that for a stream protocol like TCP, you'll need to combine it with nonblocking behaviour if you don't know the exact sizes arriving ahead of time.如果您希望程序具有响应性,通常应该使用 select 或 poll - 请注意,对于像 TCP 这样的流协议,如果您不知道提前到达的确切大小,则需要将其与非阻塞行为结合起来。

Documentation of socket.recv_into(buffer[, nbytes[, flags]]) specifies that: socket.recv_into(buffer[, nbytes[, flags]])文档规定:

Receive up to nbytes bytes from the socket, storing the data into a buffer rather than creating a new bytestring.从套接字接收最多 nbytes 字节,将数据存储到缓冲区中而不是创建新的字节串。 If nbytes is not specified (or 0), receive up to the size available in the given buffer.如果未指定 nbytes(或 0),则最多接收给定缓冲区中可用的大小。

Try to be more specific in how many bytes for data you're actually receiving from the socket by setting nbytes to a number of bytes.通过将nbytes设置为多个字节,尝试更具体地了解您实际从套接字接收的数据字节数。 Typically, messages are either delimited (eg by CRLF ) so even if you allow fewer bytes on recv function you can just wait for the delimiter to arrive;通常,消息要么是分隔的(例如通过CRLF ),因此即使您在recv函数上允许较少的字节,您也可以等待分隔符到达; or they are fixed-length, in which case you just set to that byte-length (or slightly over it).或者它们是固定长度的,在这种情况下,您只需设置为该字节长度(或稍微超过它)。

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

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