【发布时间】:2020-08-10 09:56:45
【问题描述】:
在 TCP 套接字中,您绑定然后通过 s.accept() 接受连接,但在 UDP 套接字中,您只需绑定服务器和任何人连接(如果我错了,请纠正我)所以如何控制客户端,例如,如果 5 个客户端连接到服务器关闭服务器,或者如果有人连接到服务器,向他发送一条消息,说欢迎使用服务器 感谢您的任何回答。
【问题讨论】:
标签: python sockets server udp python-3.7
在 TCP 套接字中,您绑定然后通过 s.accept() 接受连接,但在 UDP 套接字中,您只需绑定服务器和任何人连接(如果我错了,请纠正我)所以如何控制客户端,例如,如果 5 个客户端连接到服务器关闭服务器,或者如果有人连接到服务器,向他发送一条消息,说欢迎使用服务器 感谢您的任何回答。
【问题讨论】:
标签: python sockets server udp python-3.7
根据定义,UDP 没有“会话”的概念,因此它不知道它当前正在处理多少。
您需要在代码中实现某种会话管理,以决定客户端何时处于活动状态或不处于活动状态,并对此采取行动。
下面的示例代码部分应允许最多五个客户端并在 30 秒后使它们过期。
bind_ip = '192.168.0.1' ## The IP address to bind to, 0.0.0.0 for all
bind_port = 55555 ## The port to bind to
timeout = 30 ## How long before forgetting a client (seconds)
maximum = 5 ## Maximum number of clients
###
import socket
import time
## Create the socket as an internet (INET) and UDP (DGRAM) socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
## Bind to the server address and port
sock.bind((bind_ip, bind_port))
## Make a dict to store when each client contacted us last
clients = dict()
## Now loop forever
while True:
## Get the data and the address
data, address = sock.recvfrom(1024)
## Check timeout of all of the clients
for addr in clients.keys():
## See if the timeout has passed
if clients[addr] < (time.time() - timeout):
## Expire the client
print('Nothing from ' + addr + ' for a while. Kicking them off.')
clients.pop(addr)
## Check if there are too many clients and if we know this client
if len(clients.keys()) > maximum and address not in clients.keys():
print('There are too many clients connected!')
continue
## Update the last contact time
clients[address] = time.time()
## Do something with the data
print('Received from ' + str(address) + ': ' + str(data))
这绝不是最有效的方法,仅作为示例。
相关阅读:https://en.wikibooks.org/wiki/Communication_Networks/TCP_and_UDP_Protocols/UDP
【讨论】: