Alessandro Roat <alexr...@gmail.com> added the comment:

This is an example, test it with netcat (nc -u localhost 8888) on linux (ubuntu 
9.10).
Lauch it with python <scriptname>, a prompt will appear.
Type "start" to launch the server, test the server sending UDP packets with 
netcat, the lenght of packet will be correctly printed.
However, when you'll type "stop" the close will be invoked but the receiving 
thread wont stop and the join in the stop() wont never return and you will need 
to kill the python interpreter.


import socket
import threading
import sys
import select


class UDPServer:
    def __init__(self):
        self.s=None
        self.t=None
    def start(self,port=8888):
        if not self.s:
            self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.s.bind(("",port))
            self.t=threading.Thread(target=self.run)
            self.t.start()
    def stop(self):
        if self.s:
            self.s.close()
            self.t.join()
            self.t=None
    def run(self):
        while True:
            try:
                data,addr=self.s.recvfrom(1024)
                print "recv done"
                if len(data)<=0:
                    raise
                self.onPacket(addr,data)
            except:
                break
        #chiusura socket
        print "server is no more running"
        self.s=None
    def onPacket(self,addr,data):
        print len(data)


us=UDPServer()
while True:
    sys.stdout.write("UDP server> ")
    cmd=sys.stdin.readline()
    if cmd=="start\n":
        print "starting server..."
        us.start(8888)
        print "done"
    elif cmd=="stop\n":
        print "stopping server..."
        us.stop()
        print "done"
    elif cmd=="quit\n":
        print "Quitting ..."
        us.stop()
        break;

print "bye bye"

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue8831>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to