mirror of
https://github.com/Xevion/tcp-chat.git
synced 2026-01-31 06:26:11 -06:00
Handle KeyboardInterrupt properly in server mainthread
This commit is contained in:
+10
-7
@@ -1,10 +1,9 @@
|
|||||||
import logging
|
import logging
|
||||||
import socket
|
import socket
|
||||||
import sys
|
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
from shared import constants
|
|
||||||
from server import handler
|
from server import handler
|
||||||
|
from shared import constants
|
||||||
|
|
||||||
host = constants.DEFAULT_IP
|
host = constants.DEFAULT_IP
|
||||||
port = constants.DEFAULT_PORT
|
port = constants.DEFAULT_PORT
|
||||||
@@ -12,6 +11,7 @@ port = constants.DEFAULT_PORT
|
|||||||
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
server.bind((host, port))
|
server.bind((host, port))
|
||||||
server.listen(1)
|
server.listen(1)
|
||||||
|
server.settimeout(0.5)
|
||||||
|
|
||||||
logger = logging.getLogger('server')
|
logger = logging.getLogger('server')
|
||||||
logger.setLevel(logging.DEBUG)
|
logger.setLevel(logging.DEBUG)
|
||||||
@@ -21,6 +21,7 @@ clients = []
|
|||||||
|
|
||||||
# Receiving / Listening Function
|
# Receiving / Listening Function
|
||||||
def receive():
|
def receive():
|
||||||
|
try:
|
||||||
while True:
|
while True:
|
||||||
conn = None
|
conn = None
|
||||||
|
|
||||||
@@ -41,14 +42,16 @@ def receive():
|
|||||||
# Start Handling Thread For Client
|
# Start Handling Thread For Client
|
||||||
thread = threading.Thread(target=client.handle, name=client.id[:8])
|
thread = threading.Thread(target=client.handle, name=client.id[:8])
|
||||||
thread.start()
|
thread.start()
|
||||||
except KeyboardInterrupt:
|
except socket.timeout:
|
||||||
logger.info('Server closed by user.')
|
pass
|
||||||
if conn:
|
except KeyboardInterrupt as e:
|
||||||
conn.close()
|
raise e
|
||||||
break
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.critical(e, exc_info=e)
|
logger.critical(e, exc_info=e)
|
||||||
break
|
break
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.info('User stopped server manually.')
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
Reference in New Issue
Block a user