Python ServerSocket从一个单独的Thread运行

时间:2016-01-18 14:44:04

标签: python sockets serversocket python-multithreading

我想在一个单独的线程中运行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)

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

1 个答案:

答案 0 :(得分:1)

这里的问题是你将不正确数量的参数传递给SocketServer.BaseRequestHandler中的Parent方法。

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

希望它有所帮助。 改变

def __init__(self):
    self._running = True 

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