pythonsocketserver如何从线程访问主类数据

2024-09-30 05:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法,如何在python中使用SocketServer,以便在线程化服务器worker中处理主类的对象。我认为它与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()

错误消息说:

^{pr2}$

Tags: thetoimportselfcachedataservertime

热门问题