gpt4 book ai didi

Python SocketServer死锁问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:58 26 4
gpt4 key购买 nike

当我对 SocketServer 实例进行线程处理(serve_forever 方法)时,我可以在发送文本“shutdown”时轻松退出它,这正是我所期望的。但是,如果它没有线程,那么我会遇到它锁定的问题,并且我不知道如何解决这个问题。

服务器本身的基本流程是启动->监听->获取数据->从中获取命令->运行命令(这是一个插件)->返回结果。这是我使用的代码:

import SocketServer as SS

NULL_RESP = {"status" : False, "data" : "No data received."}

class ASWCP_Daemon(SS.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()

if self.data == "":
self.request.sendall(json.dumps(NULL_RESP))
return None

tmp = self.data.split(" ", 1)

cmd = tmp[0]
args = ""

try:
args = str(tmp[1]).split(conf.command_parse)
except:
pass

plugin = plugins["cmd"][cmd]['ref'].init(conf=conf, socket=self)

try:
if args[0] == "help":
self.request.sendall(plugin.help)
except IndexError:
status,data = plugin.run(args)
resp = {"status" : status, "data" : data}
self.request.sendall(json.dumps(resp))

if __name__ == "__main__":
# Log is created here; conf = config file (irrelevant to this issue)

try:
if conf.tcp:
if conf.threaded:
import threading
class ThreadedTCPServer(SS.ThreadingMixIn, SS.TCPServer):
pass

server = ThreadedTCPServer((conf.host, conf.listen_port), ASWCP_Daemon)
else:
server = SS.TCPServer((conf.host, conf.listen_port), ASWCP_Daemon)
else:
server = SS.UDPServer((conf.host, conf.listen_port), ASWCP_Daemon)

if conf.threaded:
sthread = threading.Thread(target=server.serve_forever)
#sthread.daemon = True
sthread.start()
else:
server.serve_forever()
except KeyboardInterrupt:
pass

关闭插件的运行方法是这样的:

    def run(self, *args, **kwargs):
if self.socket == None:
print "> No socket available"
return (False,"")
else:
self.socket.log.info("Shutting down daemon")
self.socket.server.shutdown()

return (True,"")

如果是线程化的,那就没问题,如果不是,那么它会到达插件中的 self.socket.server.shutdown() 方法。 self.socket 是 ASWCP_Daemon 类的实例。

最佳答案

    # Do shutdown() if threaded, else execute server_close()
if self.sysconf.threaded:
self.socket.server.shutdown()
else:
self.socket.server.server_close()

return (True,"")

self.sysconf 是守护进程的配置(问题代码中的 conf),self.socket 是引用到流处理程序。

关于Python SocketServer死锁问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17475713/

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