views:

214

answers:

4

Hi,

I would like to listen on 2 different UDP port with the same server. I use SocketServer lib for my server, and basicly it looks like that;

SocketServer.UDPServer(('', 7878),CLASSNAME)

I would like to listen on 7878 and 7879 with the same server and same file. Is that possible ? If yes how ?

Thanks in advance.

+1  A: 

Nope. Consider using Twisted.

Ignacio Vazquez-Abrams
A: 

What about threading ?!?

beratch
+2  A: 

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.

Eli Bendersky
A: 

No need to use threads for something like this. Consider http://code.google.com/p/pyev/

Amigable Clark Kant