线程套接字功能搞乱了局部变量

时间:2014-08-29 15:58:15

标签: python multithreading sockets

我正在使用TCP在Python中创建一个小型测试服务器。套接字是阻塞的,但我不认为套接字与此问题相关。我知道目前的解决方案有点丑陋和混乱,但经过大量的测试和调整才能看出哪些有效,哪些无效。

此函数在类中的每个客户端的线程中运行。

每个客户(一个类)都拥有一个名称以及之前设置的其他一些不相关的东西。

问题是每当我连接两个或多个客户端时,客户端变量被设置为最后添加的客户端,在本例中为Computer2。您还可以看到索引变量永远不会受到影响。

以下是代码:

def recieveDataFromClient(self, sock, index):
    while True:
        client = self.clients[index]
        recvStr = sock.recv(1024).decode()
        if not recvStr:
            break
        if client.name:
            print("got something from "+client.name+" on "+str(sock))
            print("Clients:")
            for client in self.clients:
                print(client.name)
            print("this client is: "+str(index)+" - "+self.clients[index].name+" aka "+client.name)

这是从Computer1发送的输出:

got something from Computer1 on <socket.socket object, fd=1044, family=2, type=1, proto=0>
Clients:
Computer1
Computer2
this client is: 0 - Computer1 aka Computer2

这是从Computer2发送的输出:

got something from Computer2 on <socket.socket object, fd=1100, family=2, type=1, proto=0>
Clients:
Computer1
Computer2
this client is: 1 - Computer2 aka Computer2

1 个答案:

答案 0 :(得分:3)

您不小心覆盖了client变量:

  client = self.clients[index]  # You assign client here
    recvStr = sock.recv(1024).decode()
    if not recvStr:
        break
    if client.name:
        print("got something from "+client.name+" on "+str(sock))
        print("Clients:")
        for client in self.clients:  # You're stomping on it here
            print(client.name)
        # Now when you use client below, its whatever came last in the for loop.
        print("this client is: "+str(index)+" - "+self.clients[index].name+" aka "+client.name)

在for循环中使用不同的名称。