如何在 python 中处理 UDP 套接字客户端

How to handle UDP socket clients in python

在您绑定的 TCP 套接字中,然后通过 s.accept() 接受连接,但在 UDP 套接字中,您只需绑定服务器和任何人连接(如果我错了请纠正我)那么如何控制客户端,例如如果5个客户端连接到服务器关闭服务器或者如果有人连接到服务器向他发送一条消息说欢迎来到服务器 感谢您的回答。

根据定义,UDP 没有 'sessions' 的概念,因此它不知道当前正在处理多少。

您需要在您的代码中实施某种会话管理来决定客户端何时处于活动状态,并据此采取行动。

下面是一个示例代码部分,最多允许五个客户端并在三十秒后使它们过期。

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