Home > Software engineering >  How can I keep a list of connected clients in a list in python?
How can I keep a list of connected clients in a list in python?

Time:11-21

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

CodePudding user response:

Not a job for a list, but a job for an associative map, which is called dictionary 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.

CodePudding user response:

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.

  • Related