python - 键盘中断线程

标签 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'

最佳答案

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

关于python - 键盘中断线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336878/

相关文章:

python - 如何在包中使用 __init__.py 文件?

java - 我们请求长时间运行,UI 在响应准备好时超时

JavaFX : How to pass value from background thread to JavaFX UI thread with Task

python - pandas - 对 DataFrame 列中的对象求和并与 DataFrame 连接

python - 来自 Python 的 Node JS Post 请求

multithreading - 使用 WaitForSingleObject() 等待线程完成

java - 线程在多核环境中是否更高效?

c - 多线程向列表无限循环插入元素

Python PyEphem 计算方位角和高度

python - 截断十进制数字 numpy float 组