如何在线程中停止udp服务器?

时间:2016-01-16 17:04:36

标签: python multithreading sockets

我在程序中写了一个udp no echo服务器,我用线程运行并听别人发送的消息。但是当我输入tl.stop()q时,我似乎无法停止使用quit。我的一些代码如下:

            class treadListen(threading.Thread):
                def __init__(self):
                    self.running = True
                    threading.Thread.__init__(self)

                def run(self):
                    address = ('localhost', 16666)
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                    sock.bind(address)
                    while True:
                        data = sock.recv(65535)
                        print "MESSAGE:{0}".format(data)
                    sock.close()

                def stop(self):
                    self.running = False
                # end of class thread_clock


            if __name__ == "__main__":
                tl = treadListen()
                tl.start()

                while True:
                    message = raw_input("CMD>")
                    if not message:
                        print "Please input command!"
                        continue
                    elif (message == 'quit') or (message == 'q'):
                        tl.stop()
                        break
                    else:
                        print "input is {0}".format(message)
                        # do something
                        continue
                print "[CONNECTION CLOSED!]"

我试图将sock.shutdown(socket.SHUT_RDWR)sock.close()添加到def停止类,但它不起作用。 如何停止线程安全?谢谢!

2 个答案:

答案 0 :(得分:1)

你的while循环while True:永远有效,所以我猜你对套接字的关闭或关闭调用永远不会起作用。

您应该将while True:更改为while self.running:,这应该可以解决问题。

答案 1 :(得分:0)

感谢ntki,rbp,st。 问题解决后使用以下代码:

            class treadListen(threading.Thread):
                def __init__(self):
                    **self.running = True**
                    threading.Thread.__init__(self)

                def run(self):
                    address = ('localhost', 16666)
                    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                    **sock.settimeout(1)**
                    sock.bind(address)
                    **while self.running:
                        try:
                            data = sock.recv(65535)
                            print "MESSAGE:{0}".format(data)
                        except Exception, e:
                            continue**
                    sock.close()

                def stop(self):
                    **self.running = False**
                # end of class thread_clock