mirror of
https://github.com/Xevion/tcp-chat.git
synced 2025-12-06 11:16:39 -06:00
Handle KeyboardInterrupt properly in server mainthread
This commit is contained in:
@@ -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,34 +21,37 @@ clients = []
|
||||
|
||||
# Receiving / Listening Function
|
||||
def receive():
|
||||
while True:
|
||||
conn = None
|
||||
try:
|
||||
while True:
|
||||
conn = None
|
||||
|
||||
try:
|
||||
# Accept Connection
|
||||
logger.debug('Waiting for connections...')
|
||||
conn, address = server.accept()
|
||||
logger.info(f"New connection from {address}")
|
||||
try:
|
||||
# Accept Connection
|
||||
logger.debug('Waiting for connections...')
|
||||
conn, address = server.accept()
|
||||
logger.info(f"New connection from {address}")
|
||||
|
||||
client = handler.Client(conn, address, clients)
|
||||
clients.append(client)
|
||||
client.request_nickname()
|
||||
client = handler.Client(conn, address, clients)
|
||||
clients.append(client)
|
||||
client.request_nickname()
|
||||
|
||||
# Inform all clients of new client, give new client connections list
|
||||
for client in clients:
|
||||
client.send_connections_list()
|
||||
# Inform all clients of new client, give new client connections list
|
||||
for client in clients:
|
||||
client.send_connections_list()
|
||||
|
||||
# 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 Exception as e:
|
||||
logger.critical(e, exc_info=e)
|
||||
break
|
||||
# Start Handling Thread For Client
|
||||
thread = threading.Thread(target=client.handle, name=client.id[:8])
|
||||
thread.start()
|
||||
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__':
|
||||
|
||||
Reference in New Issue
Block a user