我的Python聊天服务器无法正确发送消息

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

当从客户端发送发送时间的消息时,它不会发送到另一个客户端,我对 python 和套接字相当陌生,一些注释掉的代码是我尝试过但没有工作的代码

我的服务器代码:

import socket
import threading

def handle_client(client_socket):
    while True:
        data = client_socket.recv(1024)
        if not data:
            break
        message = data.decode('utf-8')
        message = str(message)

        for i in clients:
            i.send(message.encode('utf-8'))
            # i.sendall(message.encode('utf-8'))
            #i = 0
            
    
        print(f"Received message: {message}")
        #response = "Server received your message: " + message
        #client_socket.sendall(response.encode('utf-8'))
    # client_socket.close()

def main():
    global clients
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    server_socket.bind((host, port))
    \# server_socket.listen()
    print(f"Server listening on {host}:{port}")
    clients = \[\]
    names = \[\]

    while True:
        server_socket.listen()
        client_socket, client_address = server_socket.accept()
        Username = client_socket.recv(1024).decode('utf-8')
        names.append(Username)
        clients.append(client_socket)
        print(f"Accepted connection from {client_address} with name {Username}")
        # print(f"CLIENT SOCKET: {client_socket}")
        client_handler = threading.Thread(target=handle_client, args=(client_socket,))
        client_handler.start()

if __name__ == "__main__":
main()

我的客户代码:

import socket
import threading

def recive():
    data = client_socket.recv(1024)
    msg = data.decode('utf-8')
    print(f"{msg}")

def main():
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    Username = input('Username: ')
    client_socket.connect((host, port))
    client_socket.sendall(Username.encode('utf-8'))
    recive_handler = threading.Thread(target=recive)
    recive_handler.start()

    while True:
        message = input("Enter your message: ")
        client_socket.sendall(message.encode('utf-8'))

if __name__ == "__main__":
    main()

我尝试将 sendall() 更改为 send() 在 for 循环中重置 I 删除 client_socket.close()

抱歉,如果这个问题很难理解或不好,我是该平台的新手

python python-3.x windows python-sockets
1个回答
0
投票

在你的代码中,当多个socket客户端连接到服务器时是不安全的,并且当发生错误时代码会崩溃。

  • 添加客户端到客户端列表时需要加锁。
  • 这是添加
    try except
    检查所必需的。

以下代码我已测试成功!

socket服务器代码:

import socket
import threading

clients = []
clients_lock = threading.Lock()

def handle_client(client_socket, client_address):
    while True:
        try:
            data = client_socket.recv(1024)
            if not data:
                break

            message = data.decode('utf-8')
            print(f"Received message from {client_address}: {message}")

            # Broadcast message to all clients
            with clients_lock:
                for client in clients:
                    if client != client_socket:
                        client.sendall(message.encode('utf-8'))
        except ConnectionResetError:
            break

    with clients_lock:
        clients.remove(client_socket)
    client_socket.close()
    print(f"Connection closed from {client_address}")

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    server_socket.bind((host, port))
    server_socket.listen()
    print(f"Server listening on {host}:{port}")

    while True:
        client_socket, client_address = server_socket.accept()
        print(f"Accepted connection from {client_address}")

        with clients_lock:
            clients.append(client_socket)

        client_handler = threading.Thread(target=handle_client, args=(client_socket, client_address))
        client_handler.start()

if __name__ == "__main__":
    main()

socket客户端代码:

import socket
import threading

def receive():
    while True:
        try:
            data = client_socket.recv(1024)
            if data:
                msg = data.decode('utf-8')
                print(f"Received data: {msg}")
            else:
                break
        except ConnectionResetError:
            break

def main():
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 8080
    client_socket.connect((host, port))

    username = input('Username: ')
    client_socket.sendall(username.encode('utf-8'))

    receive_handler = threading.Thread(target=receive)
    receive_handler.start()

    while True:
        message = input("Enter your message: ")
        if message:
            client_socket.sendall(message.encode('utf-8'))

if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.