[Python] Non-blocking socket server running in python3 in another thread

Discussão em 'Python' iniciado por Stack, Janeiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to know the best way to run a non-blocking python3 socket server.

    I currently have code that is:

    def start(data):
    global sock
    try:

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("0.0.0.0", 8080))

    sock.listen(2)

    while True:
    #Does something
    client.close()

    except KeyboardInterrupt:
    kill()

    def kill():
    sock.close()


    In my main program, how would I make this socket server run in the background (like, in another thread) and not block the main thread so I can continue to do other things in the main thread after the endpoint is created? For example, in my main thread I would like to be able to call createEndpoint(data) and then also call some other functions and etc.

    Continue reading...

Compartilhe esta Página