Python ServerSocket 运行 来自单独的线程

Python ServerSocket running from a separate Thread

我想 运行 一个 Python serversocket class 在一个单独的线程中。为此,我修改了这段代码以支持 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 方法传递的参数数量不正确。

阅读有关 kargs and inheritance 的内容,您就会明白问题所在。简而言之,kargs 可以接受可变数量的参数。

希望对您有所帮助。 更改

def __init__(self):
    self._running = True 

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