[Python] Handling multiple connections in python with sockets

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a code which works perfectly for one connection. I have seen two options for multi-client handling but I don't really understand it. Here is the server socket code:

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listening_sock:
    listening_sock.bind(('', port))
    listening_sock.listen()
    client_soc, client_address = listening_sock.accept()
    client_soc.sendall('200#Welcome to my server!'.encode())
    print(f'Address {client_soc.getsockname()[0]} connected with port {client_soc.getsockname()[1]}')
    while True:
    # get message
    msg = client_soc.recv(1024).decode()
    # receive log print:
    print(f'"{msg}" sent from {client_soc.getsockname()[0]}')
    if 'Quit' in msg:
    client_soc.sendall('200#Thanks for using my server!'.encode())
    client_soc.close()
    elif '0' < msg.split('#')[0] <= '9': # one of the valid actions
    answer = call_action(msg.split('#')[0], db, msg.split('#')[1]) # the answer for given parameter
    client_soc.sendall("200#".encode() + answer.encode())


    If I have only one connection it works good and last thing I need to add is option for multiple-client handling. What is the shortest and easiest way to do it?

    Continue reading...

Compartilhe esta Página