简体   繁体   中英

How can I keep a list of connected clients in a list in python?

how can I keep a list of connected clients in python so that whenever I need to request a file from a specific client, I can specify which client I need the file from? Below is my code to create multithreaded for multiple connections.

def main():
    print("Starting the server")
    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ## used IPV4 and TCP connection
    server.bind(ADDR) # bind the address
    server.listen() ## start listening
    print(f"server is listening on {IP}: {PORT}")
    while True:
        conn, addr = server.accept() ### accept a connection from a client
        thread = threading.Thread(target = handle_client, args = (conn, addr)) ## assigning a thread for each client
        thread.start()


if __name__ == "__main__":
    main()

Not a job for a list , but a job for an associative map , which is called dict ionary in python.

So, you drop your connections into a dictionary, by identifying them with a key (for example, a string, or a number).

This is basic python, so I'm going to refer you to the python.org tutorial ; the first few chapters are really mandatory if you want to be able to make any progress on your own; after reading 2, 3 and 4, the "data structures" chapter is easy.

It can get complicated. To start, you could have a dict that maps client address to its connection object. For instance, you could create client_connections to do the job:

client_connections = {}

def main():
    print("Starting the server")
    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ## used IPV4 and TCP connection
    server.bind(ADDR) # bind the address
    server.listen() ## start listening
    print(f"server is listening on {IP}: {PORT}")
    while True:
        conn, addr = server.accept() ### accept a connection from a client
        client_connections[addr] = conn
        thread = threading.Thread(target = handle_client, args = (conn, addr)) ## assigning a thread for each client
        thread.start()


if __name__ == "__main__":
    main()

Now you can list client address/port numbers by client_connections.keys() and get the connection by client_connections[some_address] . These are just network level addresses, not friendly names.

You'll need remove the entry when the connection closes. And if you want more user friendly names, your protocol will have to have a way to pass that back and forth. Then you could create a new map of name to ip/port connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM