gpt4 book ai didi

从单独的线程运行的Python ServerSocket

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:05 25 4
gpt4 key购买 nike

我想在单独的线程中运行Python serversocket 类。为此,我修改了此代码以支持 python 线程:

原始文件

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print self.data

if __name__ == "__main__":
HOST, PORT = "192.168.65.1", 5001
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()

到我的文件:

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):

def __init__(self):
self._running = True

def terminate(self):
self._running = False

def setup(self):
print('{}:{} connected'.format(*self.client_address))

def handle(self):
self.data = self.request.recv(1024).strip()
print self.data

def finish(self):
print('{}:{} disconnected'.format(*self.client_address))

#if __name__ == "__main__":
def run(self):
HOST, PORT = "192.168.65.1", 5001
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()

我使用它作为主文件中的单独线程运行

Thread(target=MyTCPHandler().run, args=()).start()

但是,当我运行主 python 文件时,出现此错误

----------------------------------------
Exception happened during processing of request from ('192.168.65.1', 37997)
----------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
TypeError: __init__() takes exactly 1 argument (4 given)

首先,我对支持线程的修改是否正确?请问有人可以帮我一个忙吗?

最佳答案

这里的问题是您向 SocketServer.BaseRequestHandler 的 Parent 方法传递了错误数量的参数。

了解kargsinheritance你就会明白这个问题。简而言之,kargs 可以采用可变数量的参数。

希望有帮助。改变

def __init__(self):
self._running = True

def __init__(self, *kargs):
SocketServer.BaseRequestHandler.__init__(self, *kargs)
self._running = True

关于从单独的线程运行的Python ServerSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857432/

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