我正在使用此服务器,到目前为止,我已经修复了该服务器,因此无论何时有人写它,它都会将其发送给列表中包含的所有客户端。我如何做到这一点,使其不将消息发送给正在发送信息的客户端?我一直在试图找出答案,但是我对此有些迷茫。这是代码:
import socket
import threading
from _thread import *
from threading import Thread
clients = {}
def message(c):
while True:
data = c.recv(1024).decode("utf-8")
print("Recieved: " + str(data))
if not data:
print("Client Disconnected.")
break
# skicka meddelanden till client
for client in clients.values():
try:
client.sendall(data.encode("utf-8"))
except ConnectionAbortedError:
print("[!] Connection aborted ")
except ConnectionResetError:
print("[!] Connection reset error ")
def listener():
host = "192.168.1.77"
port = 22050
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print("\nServer has started.\n\n" + "Host: " + host + "\nPort: " + str(port))
print("______________________________________________________________________\n")
while True:
c, addr = s.accept()
print(str(addr) + " has connected.")
clients[c.fileno()] = c
threading.Thread(target=message, args=(c,)).start()
if __name__ == '__main__':
listener()
答案 0 :(得分:1)
在if
循环之后使用简单的for
语句来检查迭代中的客户端是否等于线程中的当前客户端。如果是,请跳过它:
# skicka meddelanden till client
for client in clients.values():
try:
if client == c: # skip the current client
continue
client.sendall(data.encode("utf-8"))
except ConnectionAbortedError:
print("[!] Connection aborted ")
except ConnectionResetError:
print("[!] Connection reset error ")