Domanda

A server who listens and handles connections is required for my program and, as ThreadingTcpServer does the whole job for me I decided to use it.

I noted that ThreadingTcpServer.serve_forever() is a blocking method, so I would make the thread server a thread itself. My code is:

server = None #a variable that will contain the server

def createAndStartServer():
  print "starting..."
  server = ThreadingTcpServer((socket.gethostname(),1234),MyRequestHandler)
  server.serve_forever() #blocking method
  print "stopping..."

myThread = threading.Thread(target=createAndStartServer)
myThread.start()
time.sleep(3)
server.shutdown() #this one should stop the server thread from receiving further requests

The idea is to send a shutdown to the server, this way the thread will at most serve the requests it is already serving and, after that, exits from the serve_forever() loop. This would cause the thread itself to stop as it exits from the createAndStartServer function. I don't know if it is the best method to do that but it sounds logic to me and in java I often do the same, by modifing the value of a boolean variable which handles the threading server loop...I think the shutdown method does something like that, right?

Anyway I got a:

AttributeError: 'NoneType' object has no attribute 'shutdown'

It seems that the server variable is not populated at all by the thread. Why? And while we are at it tell me if my logic is correct or you have some better idea to handle my problem.

È stato utile?

Soluzione

You are lacking of a "global server" inside your createAndStartServer().

By default, python will consider the server = Threading() as a new variable with a local scope. That explains why calling it from the main fails after with the None value.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top