Python SocketServer - 如何从线程访问主类数据
我想知道怎么在Python中使用SocketServer,这样我就能在多线程的服务器工作中使用主类的对象。我觉得这可能和SocketServer类的继承有关,但我搞不清楚怎么做。
import socket
import threading
import SocketServer
import time
class moje:
cache=[]
cacheLock=None
def run(self):
self.cacheLock = threading.Lock()
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 1234
SocketServer.TCPServer.allow_reuse_address = True
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
while True:
print time.time(),self.cache
time.sleep(2)
server.shutdown()
class ThreadedTCPRequestHandler(moje,SocketServer.StreamRequestHandler):
def handle(self):
# self.rfile is a file-like object created by the handler;
# we can now use e.g. readline() instead of raw recv() calls
data = self.rfile.readline().strip()
print "ecieved {}:".format(data)
print "{} wrote:".format(self.client_address[0])
# Likewise, self.wfile is a file-like object used to write back
# to the client
self.wfile.write(data.upper())
self.cacheLock.acquire()
if data not in self.cache:
self.cache.append(data)
self.cacheLock.release()
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
m=moje()
m.run()
错误信息显示:
File "N:\rpi\tcpserver.py", line 48, in handle
self.cacheLock.acquire()
AttributeError: 'NoneType' object has no attribute 'acquire'
1 个回答
0
moje
是一个混合类——它不能单独使用。
试试:
serv = ThreadedTCPServer() # which has moje as a mixin class
serv.run()
另请参见:Python中的多线程TCP服务器