1

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
beratch
  • 277
  • 2
  • 6
  • 8

3 Answers3

3

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
  • 263,248
  • 89
  • 350
  • 412
1

Nope. Consider using Twisted.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

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

Prof. Falken
  • 24,226
  • 19
  • 100
  • 173