Python插座 - 如何正确处理超时?

发布于 2025-01-30 03:55:17 字数 545 浏览 1 评论 0原文

使用

data, addr = sock.recvfrom(1024)

我想知道有人如何处理是否超时。假设我将数据包发送到上面所示,一切正常,除了发射器停止发送更多数据包时,接收器一侧的插座只需等待,然后继续使用新的paket。但是,我想有某种柜台等待特定的时间,并在没有新的paket进来后关闭插座。

要这样做,我必须以某种方式抓住那一刻,但我没有收到数据 的一种方法

找到了我尝试过的插座正确地做到这一点

   try:
        data, addr = sock.recvfrom(1024)
    except:
        print("connection lost")

,但它不起作用(预计已经这样做)。我还尝试了一段时间的循环:

while True:
             data, addr = sock.recvfrom(1024)

哪个有效,但是我又无法检查连接是否丢失。

有什么想法如何处理?谢谢

Using

data, addr = sock.recvfrom(1024)

i wonder how someone can handle if a timeout. Let's say i send packets over and recieve them as shown above, everything works, except that when a transmitter stops sending further packets, the socket on the reciever side just waits and continues if a new paket come. However, i would like to have some kind of counter that waits for a specific time and closes the socket after no new paket comes in.

To do so, i have to somehow catch that moment when data is no longer received but i haven't found really a way of doing it properly with socket

I've tried something like

   try:
        data, addr = sock.recvfrom(1024)
    except:
        print("connection lost")

but it doesn't work (expected that already). I also tried a while loop like so:

while True:
             data, addr = sock.recvfrom(1024)

which works, but again i cannot check if the connection is lost.

Any ideas how to deal with this? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恍梦境° 2025-02-06 03:55:17

您可以使用socket.settimeout()函数设置套接字以等待特定的接收数据。如果将套接字作为套接字创建。Sock_Dgram,则是UDP套接字。 UDP是无连接协议。使用TCP插座,您可以简单地使用recv()和send()方法。您还可以将代码放在“尝试捕获”下,如下所示,以处理套接字错误...

try:
    # Code
except socket.error as exception:
    print("socket.error : ", exception)
finally:
    pass

You can use socket.settimeout() function to set the socket to wait for a particular amount of time for receving data. If you are creating socket as socket.SOCK_DGRAM, it is a UDP socket. UDP is connectionless protocol. With TCP sockets you can simply use recv() and send() method. You can also put your code under "try catch" as shown below to handle socket error...

try:
    # Code
except socket.error as exception:
    print("socket.error : ", exception)
finally:
    pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文