显示连接到套接字服务器的所有客户端并向其发送数据

时间:2017-07-23 07:27:05

标签: python multithreading python-3.x sockets server

我有这个简单的代码:

import socket

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((host, port))
socket.listen()
while True:
    client_socket, addr = socket.accept()
    send = input("Send: ") # but I need a way to send it to all the clients connected
    if send == "devices":
    # here I'd have a list of all devices connected
    client_socket.send(send.encode())
    data = client_socket.recv(4096)
    print (data)

正如我在评论中所写,我需要一种方法来管理它们。我能怎么做?也许用_thread库?

1 个答案:

答案 0 :(得分:1)

您可以维护一个客户列表,这些客户端可以传递给在所有客户端上执行操作的外部函数。

nodejs

以上示例演示了如何一次向所有客户端发送数据。你可以使用

import socket

host = ''
port = 1000
max_connections = 5


socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((host, port))
socket.listen(max_connections)
clients = []    # Maintain a list of clients
try:
    while True:
        client_socket, addr = socket.accept()
        clients.append(client_socket)    #Add client to list on connection
        i_manage_clients(clients)       #Call external function whenever necessary
except KeyboardInterrupt:
    socket.close()

def i_manage_clients(clients):    #Function to manage clients
    for client in clients:
        client.send('Message to pass')