首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyboardInterrupt线程数

KeyboardInterrupt线程数
EN

Stack Overflow用户
提问于 2014-06-21 07:04:36
回答 2查看 1.8K关注 0票数 2

我正在编写一个支持pyBonjour的简单TCP套接字服务器。为了做到这一点,我想使用线程。问题是我如何让服务器停止...我认为下面的方法应该可以工作(根据this),但它不是

有没有更好的方法来做这件事?

代码语言:javascript
复制
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'
EN

回答 2

Stack Overflow用户

发布于 2014-06-21 07:17:35

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

票数 2
EN

Stack Overflow用户

发布于 2014-06-30 23:17:29

来自place you linked to

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

你在代码中遗漏了,所以这就是为什么他们不停下来

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

代码语言:javascript
复制
thread.daemon=True
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24336878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档