我正在使用socket
和threading
模块创建服务器。服务器允许建立多个连接。我一直在进行一些错误处理(如下面的代码所示)。但是,有一个错误我无法弄清楚该如何处理。
代码(server.py):
import socket
import threading
# import pyaudio
# import json
from os import system
system('clear')
host = socket.gethostbyname(socket.gethostname())
port = 5000
buffer_size = 2048
connected_clients = {}
# Thread for listening and accepting new connections
def client_listener():
while True:
try:
# Accepts new client
connection, address = server_socket.accept()
# Creates a new thread for each connected client
handle_client_thread = threading.Thread(target=handle_client, args=(connection, address))
handle_client_thread.start()
except ConnectionAbortedError:
pass
except OSError:
pass
except KeyboardInterrupt:
pass
# Handles each connected client in a separate thread
def handle_client(client, client_address):
try:
# Receives room number
room_number = client.recv(buffer_size).decode('utf-8')
print(f'\nConnection from {client_address[0]}:{client_address[1]} ({room_number})')
# Adds new client to 'connected_clients'
connected_clients[room_number] = client
print(connected_clients)
while True:
data = client.recv(buffer_size).decode('utf-8')
# If no data is received, close the socket
if not data:
print(f'{client_address[0]}:{client_address[1]} ({room_number}) Disconnected')
connected_clients.pop(room_number)
break
# Print received data
else:
print(f'{client_address[0]} ({room_number}): {data}')
except KeyboardInterrupt:
client.close()
connected_clients.pop(room_number)
with socket.socket() as server_socket:
try:
# Prevents [Errno 48: Address already in use]
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Binds socket to host and port
server_socket.bind((host, port))
server_socket.listen()
print(f'Server hosted on {host}:{port}')
# Starts new thread for listening for new clients
client_listener_thread = threading.Thread(target=client_listener, name=client_listener)
client_listener_thread.start()
# Prevents main thread from closing
while True:
pass
except socket.error as error_message:
print(str(error_message))
except KeyboardInterrupt:
print(': Closing server...\n')
pass
当我使用键盘中断(^ C)关闭服务器时,将引发错误消息。当我第一次按^ C时,服务器关闭。但是,第二个^ C似乎在threading
模块内引发了异常。
错误消息:
Server hosted on 10.108.249.108:5000
^C: Closing server...
^CException ignored in: <module 'threading' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1273, in _shutdown
t.join()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1032, in join
self._wait_for_tstate_lock()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1048, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):
KeyboardInterrupt
我将如何无缝处理此KeyboardInterrupt,以使程序在单个^ C上关闭而没有错误?理想的结果是让服务器关闭与每个连接的客户端的连接,关闭线程,然后最后关闭服务器本身。
答案 0 :(得分:0)
在控制台上运行脚本时,如果在键盘上按Ctrl-C
,则会向脚本进程发送SIGINT
。您可以使用signal
python模块来处理此类信号:
import signal
import sys
def my_sig_handler(sig, frame):
print('Received interrupt signal')
sys.exit(0)
signal.signal(signal.SIGINT, my_sig_handler) # Register your signal handler for SIGINT
执行此操作后,只要运行的脚本收到中断信号,就会调用my_sig_handler
。 Linux中定义了多种信号,通常最好在代码中为一些常见的信号处理程序添加信号处理程序,以使其能够正常清理并退出。
有关信号here的更多信息。