2014-08-29 65 views
0

我正在使用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) 

这里的输出,从计算机1时发送:

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 

这里的输出,从计算机2时发送:

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 
+0

您的缩进显示不正确。你能解决它,还是确认我们看到的是你真正拥有的? – 2014-08-29 16:01:38

+0

现在修复了,粘贴时意外地删除了一个标签 – Dron 2014-08-29 16:05:56

回答

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循环中使用不同的名称即可。

+0

哦,哇,我不知道我怎么会错过。谢谢。 – Dron 2014-08-29 16:07:27