Close listening socket in python thread

后端 未结 5 948
一生所求
一生所求 2021-01-04 10:07

I have a problem trying to learn about sockets for network communication. I have made a simple thread that listens for connections and creates processes for connecting clien

5条回答
  •  难免孤独
    2021-01-04 10:27

    In most cases you will open a new thread or process once a connection is accepted. To close the connection, break the while loop. Garbage collection will remove the thread or process but join will ensure none get left behind.

    Persistent sockets close when the user closes them or they timeout. Non-persistent, like static webpages will close after they've sent the information.

    Here's a good example of a persistent socket server in Python. It uses multiprocessing which means it can run across multiple cores for CPU-bound tasks. More commonly known as multithreading.

    import socket
    import multiprocessing
    
    def run():
        host = '000.000.000.000'
        port = 1212
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('', port))
        sock.listen(3)
        while True:
            p = multiprocessing.Process(target=worker, args=sock.accept()).start()
    def worker(conn, addr):
        while True:
            if data == '':
                #remote connection closed
                break
             if len(dataList) > 2:
                # do stuff
                print 'This code is untested'
    
    run()
    

提交回复
热议问题