我想在服务器的handle函数内调用一个方法来执行它作为一个新线程。我想将请求作为参数传递,如下所示:
class serviceData(SocketServer.BaseRequestHandler):
def handle(self):
def dataTransfer(req):
data = 'dummy'
while len(data):
#data = self.request.recv(1024)
data = req.recv(1024)
print str(data)
result = 'hi'
req.sendall(str(result))
print "Client exited"
req.close()
try:
print "Client connected with ", self.client_address
thread.start_new_thread( dataTransfer, (self.request, ) )
except Exception, e:
print e
print "Error: unable to start thread"
我收到以下错误:
data = req.recv(1024)
File "usr/lib/python2.7/socket.py" line 170, in dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
任何人都知道我做得不好吗?
答案 0 :(得分:1)
我找到了解决方案。将套接字服务器和线程与ThreadedTCPServer
混合。所以:
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
server = ThreadedTCPServer( ('', 1520), service )
server.serve_forever()
通过这种方式,def handle(self): ......
为每个新连接创建一个新线程。