I have a simple python socket server and I want my client to be able to open/ close a thread process over the duration of multiple connections (ie I don’t want to keep my client-server connection open between requests). A simplified version of the server looks like this:
_bottle_thread = None # I have tried this and a class variable
class CalibrationServer(socketserver.BaseRequestHandler):
allow_reuse_address = True
request_params = None
response = None
bottle_thread = None
def handle(self):
self.data = self.request.recv(1024).strip()
self.request_params = str(self.data.decode('utf-8')).split(" ")
method = self.request_params[0]
if method == "start": self.handle_start()
elif method == "stop": self.handle_stop()
else: self.response = "ERROR: Unknown request"
self.request.sendall(self.response.encode('utf-8'))
def handle_start(self):
try:
bottle = self.request_params[1]
_bottle_thread = threading.Thread(target=start, args=(bottle,))
_bottle_thread.start()
self.response = "Ran successfully"
print(_bottle_thread.is_alive(), _bottle_thread)
except Exception as e:
self.response = f"ERROR: Failed to unwrap: {e}"
def handle_stop(self):
print(_bottle_thread)
if _bottle_thread and _bottle_thread.is_alive():
_bottle_thread.join() # Wait for the thread to finish
self.response = "Thread stopped successfully"
else:
self.response = "No active thread to stop"
if __name__ == "__main__":
HOST, PORT = LOCAL_IP, CAL_PORT
with socketserver.TCPServer((HOST, PORT), CalibrationServer) as server:
server.serve_forever()
The process starts fine, but when my connection with the server is closed, I can no longer access the _bottle_thread
. It is just re-initialized as None
. I only have one master computer communicating with the server and will only need one instance of start
running. I have tried using class variables to hold it and using global variables. I have also tried using Threading and Forking TCP servers. How can I access that thread to shut it down? Will I need to change it so the connection is always open? Is there another way to tackle this problem? I want to use a server so I can more easily control this process because it will be running on 8 different computers at a time but am totally open to other ideas (I tried Ansible it didn’t work for me). Thanks!