[issue8831] recv and recvfrom on UDP socket do not return/throw exception after a close()

Alessandro Roat report at bugs.python.org
Thu May 27 12:52:27 CEST 2010


Alessandro Roat <alexroat at 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 <report at bugs.python.org>
<http://bugs.python.org/issue8831>
_______________________________________


More information about the Python-bugs-list mailing list