如何解决套接字消息不显示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 举报,一经查实,本站将立刻删除。