0

I'm looking for a way how to use SocketServer in python in order to work with a objects of the main class within the threaded server workers. I presume its linked to the proper inheritance of the SocketServer classes, but I cannot figure it out

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()

Error message say:

  File "N:\rpi\tcpserver.py", line 48, in handle
    self.cacheLock.acquire()
AttributeError: 'NoneType' object has no attribute 'acquire'

1 Answers1

0

moje is a mixin class -- it doesn't work by itself.

try:

serv = ThreadedTCPServer() # which has moje as a mixin class
serv.run()

see also: Multi Threaded TCP server in Python

Community
  • 1
  • 1
johntellsall
  • 14,394
  • 4
  • 46
  • 40