Handle KeyboardInterrupt properly in server mainthread

This commit is contained in:
Xevion
2022-06-12 15:27:13 -05:00
parent 64a5dd8c20
commit bcf852d5aa

View File

@@ -1,10 +1,9 @@
import logging
import socket
import sys
import threading
from shared import constants
from server import handler
from shared import constants
host = constants.DEFAULT_IP
port = constants.DEFAULT_PORT
@@ -12,6 +11,7 @@ port = constants.DEFAULT_PORT
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(1)
server.settimeout(0.5)
logger = logging.getLogger('server')
logger.setLevel(logging.DEBUG)
@@ -21,6 +21,7 @@ clients = []
# Receiving / Listening Function
def receive():
try:
while True:
conn = None
@@ -41,14 +42,16 @@ def receive():
# Start Handling Thread For Client
thread = threading.Thread(target=client.handle, name=client.id[:8])
thread.start()
except KeyboardInterrupt:
logger.info('Server closed by user.')
if conn:
conn.close()
break
except socket.timeout:
pass
except KeyboardInterrupt as e:
raise e
except Exception as e:
logger.critical(e, exc_info=e)
break
except KeyboardInterrupt:
logger.info('User stopped server manually.')
return
if __name__ == '__main__':