Sure you can, using threads. Here's a server:
import SocketServer
import threading
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "%s wrote:" % self.client_address[0]
print data
socket.sendto(data.upper(), self.client_address)
def serve_thread(host, port):
server = SocketServer.UDPServer((host, port), MyUDPHandler)
server.serve_forever()
threading.Thread(target=serve_thread,args=('localhost', 9999)).start()
threading.Thread(target=serve_thread,args=('localhost', 12345)).start()
It creates a server to listen on 9999 and another to listen on 12345.
Here's a sample client you can use for testing this:
import socket
import sys
HOST, PORT = "localhost", 12345
data = 'da bomb'
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)
print "Sent: %s" % data
print "Received: %s" % received
Note: this was taken from the docs of the SocketServer
module, and modified with threads.