问题:服务器只向最新的客户端发送数据。
解释:
我有一个名为User_list
. 此列表包含两种类型的信息:连接和作为每个连接属性的用户名。
如果有人连接,服务器会收到一个用户名,检查该用户名是否在它的列表中,如果发现不在,则向每个人发送整个用户名列表,并添加最新的用户名。除了它似乎只将它发送给最新的客户。
这是发生的事件的幻灯片。(命令提示符是客户端)
我还想我会在Pastebin上添加服务器代码:
# Owatch's Multi-Threading Username Sever. (Because the select module can suck it)
from socket import *
import threading
import os
import csv
import sys
# Defining Important Information
User_List = []
Connections_List = []
# Making a thread class for each connection recieved.
class Client(threading.Thread):
def __init__(self,conn):
super(Client, self).__init__()
self.conn = conn
self.username = self.conn.recv(1024).decode()
if not any(user.username == self.username for user in User_List):
print("New guy")
# Add new guy to the list
User_List.append(self)
# Get everyone's names
current_userlist = [user.username for user in User_List]
# Send everyone's names to everyone
for x in User_List:
conn.send(x.username.encode()) # <--- Key line to the problem
U_HOST = input("Host: ")
U_PORT = input("Port: ")
SS = socket(AF_INET,SOCK_STREAM)
SS.bind((U_HOST,int(U_PORT)))
SS.listen(2)
while True:
Connection,Address = SS.accept()
Connections_List.append(Address)
print("Connection Taken, and address added to list")
CX = Client(Connection)
CX.start()
如果您想修改它,这也是客户端:
from socket import *
import threading
import os
import csv
Username = ("Owatch")
# ^^ Change Username to make a new Client!!
host = input("Host: ")
port = input("Port: ")
try:
ss = socket(AF_INET,SOCK_STREAM)
ss.connect((host,int(port)))
except IOError:
print("Console: Error Encountered During Username Accuasition")
ss.send(Username.encode())
print("\n Username Sent...")
while True:
try:
print("\nWaiting to Recieve Data")
data = ss.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data == Username:
print("It's one of ours!")
else:
Client_Username = translated_data
print ("Foreign Username is set to be: ", Client_Username)
except Exception as e:
print (vars(e))
谢谢你的时间。