在TCP套接字中,您绑定然后通过s.accept()接受连接,但是在UDP套接字中,您仅绑定服务器,任何人都可以连接(如果我错了,请纠正我),因此如何控制客户端,例如如果5个客户端连接到服务器,则关闭服务器或如果有人连接到服务器,向他发送一条消息,说欢迎来到服务器。谢谢回答。
根据定义,UDP没有“会话”的概念,因此它不知道当前正在处理多少个会话。
您将需要在代码中实现某种会话管理,以决定客户端何时处于活动状态或不处于活动状态,并对此采取措施。
下面是一个示例代码部分,该部分应最多允许五个客户端并使它们在三十秒后过期。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句