如何向Python中的TCP IP服务器中的所有客户端线程发送消息



我正在尝试在Python中构建TCP IP服务器。我的目标是在客户端上运行命令。要运行一个命令,您必须在服务器中键入" CMD命令"。我以前从未使用过线程,现在我似乎找不到如何将要执行的命令发送到客户端线程。谁能向我指向正确的方向?

到目前为止我的代码:

    import socket
    import sys
    from thread import *
    HOST = ''
    PORT = 8884
    clients = 0
    connected_id = ""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print 'Socket created'
    # Bind socket to local host and port
    try:
        s.bind((HOST, PORT))
    except socket.error, msg:
        print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
        sys.exit()
    print 'Socket successfully binded'
    # Start listening on socket
    s.listen(10)
    print 'Socket is listening'

    # Function for handling connections.
    def clientthread(conn):
        # Sending message to connected client
        conn.sendall('hello')  # send only takes string
        global clients
        # loop until disconnect
        while True:
            # Receiving from client
            data = conn.recv(1024)
            if data.lower().find("id=-1") != -1:
                clients += 1
                print("new client ID set to " + str(clients))
                conn.sendall("SID=" + str(clients))
            if not data:
                break
        # If client disconnects
        conn.close()
    def addclientsthread(sock):
        # start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function
        conn, addr = sock.accept()
        print('Client connected on ' + addr[0])
        start_new_thread(clientthread, (conn,))
    def sendallclients(message):
        # send msg to all clients
        tmp = 0
    # now keep talking with the clients
    start_new_thread(addclientsthread, (s,))
    usr_input = ""
    while str(usr_input) != "Q":
        # do stuff
        usr_input = raw_input("Enter 'Q' to quit")
        if usr_input.find("cmd") == 0:
            sendallclients(usr_input[3:])
        if usr_input.find("hi") == 0:
            sendallclients("hey")
    s.close()

保留客户端插座的列表,并在列表上循环以发送每个命令:

cons = [con1, con2, ...]
...
for con in cons:
    con.send(YOUR_MESSAGE)

首先制作客户端列表:

my_clients = [] 

然后您可以修改addclientsthread将新客户列为列表:

def addclientsthread(sock): 
    global my_clients
    conn, addr = sock.accept()
    my_clients += [conn]
    print('Client connected on ' + addr[0])
    start_new_thread(clientthread, (conn,))

sendallclients功能中的my_clients下一个迭代:

def sendallclients(message): 
    for client in my_clients : 
        client.send(message)

现在所有客户均应接收message

最新更新