【问题标题】:How to handle UDP socket clients in python如何在 python 中处理 UDP 套接字客户端
【发布时间】:2020-08-10 09:56:45
【问题描述】:

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

【问题讨论】:

    标签: python sockets server udp python-3.7


    【解决方案1】:

    根据定义,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

    【讨论】:

    • 非常感谢,但是服务器可以知道有一个客户端连接到服务器而没有客户端发送消息,因为我看到他只知道服务器收到消息或数据时客户端的地址来自客户端而不是客户端连接时
    • 由于 UDP 的工作方式,客户端不会连接到服务器,除非它正在向它发送数据。 UDP 通常被称为“无连接”协议。作为一个类比,将 TCP 想象为使用软管,每端都有一个人,而 UDP 使用水桶,一个人移动水桶(客户端),一个人等待水桶(服务器)。 TCP 服务器将知道在连接软管时可以接收到水(数据)。等待存储桶的 UDP 服务器不知道会有多少个存储桶,以及对方是不是出去吃午饭了,还是没有更多的存储桶
    • 添加了 wikibooks 文章的链接,希望能比我更清楚地说明问题。您只能在 SO 评论中容纳这么多。
    • 谢谢,为什么我在尝试使用 udp 套接字发送数据(图像)时收到消息太长错误
    • 您不能在一个 IP 数据报中发送超过 64k 的数据。如果要传输更多,则需要使用多个数据报。这意味着您需要在发送时对图像进行分段,并在接收代码中重新组装它们。由你来处理丢失和乱序的数据包,你也应该使用更接近 1500 字节的数据报(除非你知道你的网络支持“巨型帧”)
    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2014-11-19
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多