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

问题描述 投票:0回答:1

python套接字向客户端发送例如“超时”的方法,如果客户端未发送任何内容例如5秒钟然后关闭连接(我可以关闭连接,这将是c.close(),但据我所知在这种情况下)?对于这样的高级套接字编程,我是一个初学者。我不知道要尝试什么,因此无法发送“我尝试过的”代码。我能发送的就是服务器的当前代码。

import socket
from random import *
s = socket.socket()
s.bind(("localhost",int(input("Port\n>>> "))))
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()
python sockets wait
1个回答
0
投票
仅设置超时时间?

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

© www.soinside.com 2019 - 2024. All rights reserved.