【问题标题】:How to know which client is sending message to the server如何知道哪个客户端正在向服务器发送消息
【发布时间】:2015-05-30 09:59:41
【问题描述】:

以下是我目前的服务器代码

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

以上只是接受连接等的多线程函数。 我想检查哪个客户端发送了消息,因为一次只允许一个客户端发送消息。而且,发送消息的客户端只有在所有其他客户端都轮流发送消息后才能再次发送消息。我确实知道我上面的方法“if 语句”是不正确的。 在上面的代码中,服务器只是从客户端接收消息和名称并将其发送给所有客户端。连接的客户信息存储在列表中

【问题讨论】:

  • 你见过chatserver.py吗?
  • 你似乎把它弄反了。由于这是多线程的,因此将有多个线程运行此函数。每个线程只会与一个客户(您从s.accept() 获得的客户)交谈,因此当您recv 时,毫无疑问它来自谁。
  • @theSmallNothing 我明白你的意思。但是,除了 main() 中的一个,我如何才能锁定其他线程?

标签: python client-server


【解决方案1】:

我想我得到了你想要的东西。您想要的是一个类似于 round-robin 消息传递系统的系统,其中每个客户端都有一个 turn 来重新传输其消息。

为了让它工作,你需要以某种方式识别它是哪个线程的turn

我这样做的方法是让主函数增加一些全局变量,线程可以将其与它们的 id 进行比较(这可能是它们在all_clients 数组中的客户端信息索引)。

如果 id 匹配,则线程可以recv。 main 函数需要知道何时递增到下一个线程 id,因此我们可以在收到消息后使用 Event 实例和 set 它。

# 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-05
    • 2013-06-24
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多