消息程序在被告知时不会退出()

问题描述 投票:0回答:1

我正在尝试用 python 创建一个消息系统,其中两台运行相同程序的计算机可以相互来回发送消息。我已经完成了这一点,并补充说,如果我输入“back”,它将退出程序。问题是“back”命令仅适用于客户端,在服务器端它显示输入了“back”并打印“exiting”,但它不会关闭服务器,但仍然在监听客户端虽然已经退出了。

这是我的代码

import socket
import threading
import sys
import time

# Configuration
SERVER_HOST = 'localhost'  # Server IP address
SERVER_PORT = 12345        # Port to listen on / connect to
BUFFER_SIZE = 1024

clients = []  # List to keep track of connected clients
client_socket = None  # To keep track of the current client's socket
shutdown_flag = threading.Event()  # Event to signal shutdown

def handle_client(conn_socket):
    global shutdown_flag
    while not shutdown_flag.is_set():
        try:
            message = conn_socket.recv(BUFFER_SIZE).decode('utf-8')
            if message:
                if message.upper() == 'BACK':
                    print("Client requested shutdown.")
                    shutdown_flag.set()
                    broadcast("Server is shutting down.", conn_socket)
                    break
                print(f"Received: {message}")
                broadcast(message, conn_socket)
            else:
                break
        except:
            break
    remove(conn_socket)
    conn_socket.close()

def broadcast(message, sender_socket):
    for client in clients:
        if client != sender_socket:
            try:
                client.send(message.encode('utf-8'))
            except:
                remove(client)

def remove(socket_to_remove):
    if socket_to_remove in clients:
        clients.remove(socket_to_remove)

def start_server():
    global shutdown_flag
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((SERVER_HOST, SERVER_PORT))
    server.listen(5)
    print(f"Server started on {SERVER_HOST}:{SERVER_PORT}")

    while not shutdown_flag.is_set():
        try:
            conn_socket, addr = server.accept()
            clients.append(conn_socket)
            print(f"Connection from {addr}")
            threading.Thread(target=handle_client, args=(conn_socket,)).start()
        except:
            if shutdown_flag.is_set():
                break

    # Clean up server
    server.close()
    print("Server shut down.")

def receive_messages():
    global client_socket, shutdown_flag
    while not shutdown_flag.is_set():
        try:
            message = client_socket.recv(BUFFER_SIZE).decode('utf-8')
            if message:
                print(f"Message: {message}")
            else:
                break
        except:
            break
    shutdown_flag.set()  # Signal shutdown to the server
    client_socket.close()

def send_messages():
    global client_socket, shutdown_flag
    while not shutdown_flag.is_set():
        message = input()
        if message.upper() == 'BACK':
            print("Exiting...")
            shutdown_flag.set()
            client_socket.close()
            sys.exit()
        client_socket.send(message.encode('utf-8'))

def start_client():
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((SERVER_HOST, SERVER_PORT))

    threading.Thread(target=receive_messages).start()
    threading.Thread(target=send_messages).start()

def main():
    global client_socket
    try:
        # Attempt to connect to the server
        test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        test_socket.connect((SERVER_HOST, SERVER_PORT))
        test_socket.close()
        print("Connected to the server. Running as client.")
        start_client()
    except (ConnectionRefusedError, socket.gaierror):
        print("Server not found. Starting server.")
        server_thread = threading.Thread(target=start_server)
        server_thread.start()
        # Wait a moment for the server to start up
        time.sleep(1)
        start_client()

if __name__ == "__main__":
    main()

我只需要帮助弄清楚如何使“后退”命令关闭服务器、客户端并退出程序。

这是客户端输入“back”时客户端的输出:client'back'

这是服务器端输入“back”时的输出:server'back'

如此处所示,它不会退出程序,客户端仍然可以发送消息:still receiving

python python-3.x server client messaging
1个回答
0
投票

消息程序在被告知时不会退出() 您的 send_messages 函数似乎在向服务器发送“返回”消息之前终止。您可以尝试在 if 子句中终止之前发送消息。尝试像这样交换顺序:

def send_messages():
    global client_socket, shutdown_flag
    while not shutdown_flag.is_set():
        message = input()
        client_socket.send(message.encode('utf-8'))
        if message.upper() == 'BACK':
            print("Exiting...")
            shutdown_flag.set()
            client_socket.close()
            sys.exit()

如果服务器和客户端不是来自同一进程,则关闭标志将被设置,但仅限于客户端。

© www.soinside.com 2019 - 2024. All rights reserved.