简体   繁体   中英

Check if a Client is Still Connected - Python Socket Programming using UDP

Im currently developing a chat application using UDP. How will I tell if the client is still connected to my server or still running? Below is my code:

 for i, addr in enumerate(self.all_addresses):    
        try:               
            self.socket.sendto(str.encode(''), ('<broadcast>', int(addr[1])))


        except e:              
            del self.all_addresses[i]
            continue

self.all_addresses contains the ip and port of the clients binded to the server. In the code above, I was testing whether if I send blank message to the client and it doesn't throw error, then it means it still connected. Unfortunately, the code is not working, even if the client is not running anymore, the code doesn't throw an exception. Please help me with my problem. thanks.

UDP has no concept of “connection”, so you'll have to implement that logic at the application layer. Eg have each client send a “hi, I'm still here” packet to the server every few seconds. If the server sees that (some larger number of) seconds have passed without receiving any packets from a given client, the server can assume that client has gone away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM