0
votes

I would like to implement an UDP server with Python.

I want to be able to wait for some clients to connect and chat with others at the same time.

I tried to use an SocketServer implementation

import SocketServer

class MyUDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        print("{} wrote:".format(self.client_address))
        print("data -> ", data)

        socket.sendto(data.upper(), self.client_address)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
    server.serve_forever()

With this implementation, I can send data from different clients to this server.

To be clear, what I want to do is to go in another function when a client sent UDP data to the server to be able to communicate with him. But at the same time, I still want other clients be able to send UDP data. I guess multithreading will be a solution ?

I'm not sure to be clear...

1

1 Answers

3
votes

UDP is connectionless. So you can receive messages from multiple clients with just the single SocketServer that you have, and distinguish clients from each other using client_address. You don't need threads or multiple processes.

Since it's a chat server, outgoing messages are probably always in response to incoming ones, but if you want to be able to send unsolicited messages as well, you should replace serve_forever() with handle_request() and set self.timeout in __init__(). This way you can check whether extra actions need to be performed periodically, e.g. once a minute you could send heartbeats or whatever.