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

时间:2017-04-14 14:16:09

标签: python tcp server ip client

我试图在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()

2 个答案:

答案 0 :(得分:0)

保留客户端套接字列表并在列表上循环以向每个套接字发送命令:

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

答案 1 :(得分:0)

首先制作一份客户名单:

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,))

接下来迭代my_clients函数中的sendallclients

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

现在所有客户都应该收到message