I'm developing a small server system and I need to turn the server off whenever I type "exit()" into the console (the input is handled from another thread) I was wondering if there is a way to terminate the main thread while the socket is awaiting data. I've already tried using _thread.interrupt_main() with a keyboardInterrupt exception in a try block but it didn't work. I also tried os._exit() which worked but it doesn't clean up so I decided not to use it. My code:
import socket
import _thread
import os
clear = lambda: os.system("cls")
try:
Server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
Server.bind(("localhost",port))
Server.listen(2)
clear()
print("--------------------------------------")
print("Server running on port %s" % str(port))
print("--------------------------------------")
except Exception:
print("error while starting server")
input()
exit()
def control():
while True:
command = input()
if command == "exit()":
#interrupt code here
_thread.start_new_thread(control,())
while True:
con,ip = Server.accept()
print(str(ip) + " Connected")
try:
cmd = str(con.recv(1024).decode()) #<-- interrupt this line
except Exception:
print("Error")