Python - 套接字 - 向所有客户端发送消息 - 列表索引超出范围

时间:2016-03-05 21:59:30

标签: python list sockets

我有一个server.py文件应该处理多个客户端(有点像聊天)但是如果我尝试将从客户端收到的消息发送给其他客户端,我会收到list index out of range错误。< / p>

错误在第15行 - 在for循环

中提高

这是我的server.py:

import socket
import threading

DEFAULT_SIZE = 256
client_list = []


def handle_client(connection, client_id):
    client_name = receive_message(connection, DEFAULT_SIZE)
    while 1:
        message = receive_message(connection, DEFAULT_SIZE)
        print("%s: %s" % (client_name, message))

        for c in client_list:
            connection = c[0]
            connection.sendall(client_name.encode())
            connection.sendall(message.encode())


def receive_message(connection, size):
    message = connection.recv(size)
    return message.decode("UTF-8")

server_address = ("localhost", 4000)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(server_address)
print("Server bound. Now waiting for connections...\n")

server.listen(5)

i = 0
while 1:
    client_list.append([])
    client, address = server.accept()
    client_list[i].append(client)
    client_list[i].append(address)

    print("[New connection from %s]:" % client_list[i][1][0])

    thread = threading.Thread(target=handle_client, args=(client_list[i][0], i))
    thread.start()

    i += 1

server.close()

1 个答案:

答案 0 :(得分:1)

您的代码中有race condition

while 1:
    client_list.append([])
    client, address = server.accept()
    client_list[i].append(client)
    client_list[i].append(address)

您向client_list附加一个空列表;然后accept入站连接;当收到新连接时,您将其详细信息放在列表中。但是当该线程位于accept时,正在访问client_list的另一个线程现在将看到仅[]的项目;而且我们知道:

>>> [][0]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list index out of range

当该异常被打印到终端时,发生错误的客户端线程也被终止。

解决方案是在accept之后附加客户端结构,并且仅在所有数据存在之后:

while 1:
    client, address = server.accept()
    client_info = [client, address]
    client_list.append(client_info)