套接字消息不显示python聊天应用

问题描述

我用python在套接字中创建了我的第一个“聊天应用”。我发送聊天有问题。客户端2不会从服务器(来自客户端1)获得每(平均)第5-6条消息,它是在我移至客户端2并发送新消息时出现的(然后显示以前发送给它的消息) 。 但是我注意到来自客户端1的消息没有传到客户端2,有100%到达了服务器端,只是没有发送给其他客户端。

这是服务器端代码

import socket
import threading
import pickle

HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER,PORT)
FORMAT = "utf-8"
disCONNECT_MESSAGE = "!disCONNECT"


server = socket.socket(socket.AF_INET,socket.soCK_STREAM)
server.bind(ADDR)

clients = []


def handle_client(conn,addr):
    print(f"[NEW CONNECTION] {addr} connected.")
    print("[ACTIVE CONNECTIONS] " + str(threading.active_count() - 1))


    connected = True
    while connected:
        #thread = threading.Thread(target=client_msg_update,args=(conn,addr))
        #thread.start()
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            print(f'{addr}] {msg}')

            for connection in clients:
                if connection != conn:
                    connection.send(msg.encode(FORMAT))
                    print(f"sent to {connection}")


            #conn.send("msg recieved".encode(FORMAT))


            if msg == disCONNECT_MESSAGE:
                connected = False



    print(f"[{addr}] client has disconnected.")
    conn.close()



def server_start():
    server.listen()
    print(f"[SERVER STARTED] Server is online on {SERVER}")
    while True:
        conn,addr = server.accept()
        clients.append(conn)
        thread = threading.Thread(target=handle_client,addr))
        thread.start()

print("[STARTING] - Server is starting...")

server_start()

这是客户端代码

import socket
import pickle
import threading


HEADER = 64
PORT = 5050
SERVER = "LOCAL_IP"
disCONNECT_MESSAGE = "!disCONNECT"
ADDR = (SERVER,PORT)
FORMAT = "utf-8"

client = socket.socket(socket.AF_INET,socket.soCK_STREAM)
client.connect(ADDR)

def rec_messages():
    message = client.recv(2048).decode(FORMAT)
    if message:
        print(message)


def send_msg(msg):
    message = msg.encode(FORMAT)
    message_length = len(message)
    send_length = str(message_length).encode(FORMAT)
    send_length += b" " * (HEADER - len(send_length))
    client.send(send_length)
    client.send(message)


while True:
    thread = threading.Thread(target=rec_messages)
    thread.start()
    msg = str(raw_input())
    if msg:
        send_msg(msg)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)