KeyboardInterrupt线程

时间:2014-06-20 23:04:36

标签: python multithreading

我正在编写一个支持pyBonjour的简单TCP套接字服务器。为此,我想使用线程。问题是我如何让服务器停止...我认为以下应该有效(根据this)但它不是

有没有更好的方法来做到这一点(有效)..

import SocketServer
import threading
import pybonjour
import select
import time

class BonjourThread(threading.Thread):        
    def run(self):
        sdRef = pybonjour.DNSServiceRegister(name = 'MacroServer - Mac',
                                     regtype = '_macroserver._tcp',
                                     port = 12000,
                                     callBack = self.bonjour_register_callback)

        while True:
            ready = select.select([sdRef], [], [])
            if sdRef in ready[0]:
                pybonjour.DNSServiceProcessResult(sdRef)

    def bonjour_register_callback(self, sdRef, flags, errorCode, name, regtype, domain):
        if errorCode == pybonjour.kDNSServiceErr_NoError:
            print 'Bonjour started'


class TCPThread(threading.Thread):
    def run(self):
        try:
            HOST, PORT = "localhost", 12000
            server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
            print 'TCP server started'
            server.serve_forever()
        except KeyboardInterrupt:
            print 'Closing Down'
            exit()

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        try:
            # self.request is the TCP socket connected to the client
            self.data = self.request.recv(1024).strip()
            print "{} wrote:".format(self.client_address[0])
            print self.data
            # just send back the same data, but upper-cased
            self.request.sendall(self.data.upper())
        except KeyboardInterrupt:
            print 'Closing Down'
            exit()

if __name__ == "__main__":
    try:
        thread1 = TCPThread()
        thread1.start()
        thread2 = BonjourThread()
        thread2.start()
        while True: time.sleep(100)
    except (KeyboardInterrupt, SystemExit):
        print 'Received keyboard interrupt, quitting threads.\n'
    finally:
        print 'And its bye from me'

2 个答案:

答案 0 :(得分:2)

在python中,只有主线程获取KeyboardInterrupt信号。您希望如何处理套接字服务器及其各种客户端的终止可能会变得复杂。我已经创建了日志记录服务器,我将套接字保存在主列表中,由锁保护,然后将它们全部关闭,然后等待键盘中断终止。您甚至可以将线程标记为守护进程并退出 - 让操作系统清理套接字。

答案 1 :(得分:2)

来自place you linked to

  

thread.daemon = True会导致线程在主进程结束时终止。

您在代码中遗漏的

,这就是为什么他们不会停止

对于更好的方法,你可以创建自己的信号处理程序并终止你的线程,但不确定它是否比任何更好:

thread.daemon=True