Python 如何知道哪个客户端正在向服务器发送消息
以下是迄今为止我的服务器代码Python 如何知道哪个客户端正在向服务器发送消息,python,client-server,Python,Client Server,以下是迄今为止我的服务器代码 def multipleClients(): global counter=0 conn, addr = s.accept() counter=counter+1 all_clients.append(conn) print "is connected :D :)", addr i=0 name= conn.recv(1024) while True: while i<counte
def multipleClients():
global counter=0
conn, addr = s.accept()
counter=counter+1
all_clients.append(conn)
print "is connected :D :)", addr
i=0
name= conn.recv(1024)
while True:
while i<counter:
if all_clients[counter] == conn #comparing the current client with the one which sent the message:
name=conn.recv(1024)
data= conn.recv(1024)
if not data:
break
print repr(name),":"
print "message is :", repr(data)
for c in all_clients:
n= name,":"
c.sendall(data)
counter=0
以上只是接受连接等的多线程函数。
我想检查哪个客户端发送了消息,因为一次只允许一个客户端发送消息。此外,发送消息的客户端只能在所有其他客户端轮流发送消息时再次发送消息。我知道我的上述方法如果陈述不正确。
在上面的代码中,服务器只是从客户端接收消息和名称,并将其发送给所有客户端。连接的客户信息存储在列表中我想我知道你在找什么。您需要的是一个类似于循环消息传递系统的系统,其中每个客户机有一次机会重新传输其消息 为了使这项工作,你需要某种方法来确定该轮到哪个线程 我这样做的方法是让main函数增加一些全局变量,线程可以将这些变量与它们的id进行比较,id可以是all_clients数组中的客户机信息索引 如果id匹配,那么线程就可以recv。主函数需要知道何时增加到下一个线程id,因此我们可以使用实例并在收到消息后设置它
# in this example, current_id and recvd_event are global variables, since global variables
# are generally considered a bad coding practice they also could be wrapped in a class and
# passed in.
def multipleClients():
conn, addr = s.accept()
# the number of clients at this moment is unique, so we can use it as an id
client_id = len(all_clients)
all_clients.append(conn)
# .. do other stuff ..
while True:
if client_id == current_id:
# receive, retransmit, etc..
recvd_event.set()
def main():
global current_id
# .. set up server ..
current_id = 0
recvd_event = threading.Event()
while True:
# .. select incoming connection ..
# .. create thread ..
if recvd_event.isSet():
# received a message, next thread's turn
# increments current_id and wraps around at end of client list
current_id = (current_id + 1) % len(all_clients)
recvd_event.clear()
你看到了吗?你好像倒过来了。由于这是多线程的,因此将有多个线程运行此函数。每个线程只会与一个客户机(您从s.accept获得的客户机)进行对话,因此当您接收到该线程时,毫无疑问它来自谁。@我完全不明白您的意思。但是除了主线程中的一个线程外,我如何锁定其他线程呢?