gpt4 book ai didi

python - 键盘中断线程

转载 作者:行者123 更新时间:2023-11-28 22:49:05 25 4
gpt4 key购买 nike

我正在编写一个支持 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com