Python 套接字在 5 秒内未收到数据后向客户端发送消息



python套接字的一种发送方式,例如:如果客户端没有发送任何内容,则向客户端发送"超时" 例如 5 秒,然后关闭连接(我可以关闭连接,这将是 c.close((,但据我所知在这种情况下(?当涉及到像这样的更高级的套接字编程时,我是一个初学者。 我不知道该尝试什么,所以无法发送"我尝试过"的代码。我所能发送的只是我当前的服务器代码。

import socket
from random import *
s = socket.socket()
s.bind(("localhost",int(input("Portn>>> "))))
s.listen(1)
while True:
c,a = s.accept()
data = c.recv(1024)
#Somewhere here, it would wait for 5 sec for a message to come and if not then:
c.send("Timeout".encode())
c.close()

只是设置了超时?

s.settimeout(5.0)
data = c.recv(1024)
if(not data):
c.send(b"Timeout")
c.close()

最新更新