Close listening socket in python thread

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

A dirty solution which allows to exit your program is to use os._exit(0).

def stop(self):
    self.socket.close()
    os._exit(0)

note that sys.exit doesn't work/blocks as it tries to exit cleanly/release resources. But os._exit is the most low level way and it works, when nothing else does.

The operating system itself will release the resources (on any modern system) like when doing exit in a C program.


One way to get the thread to close seems to be to make a connection to the socket, thus continuing the thread to completion.

def stop(self):
    self.running = False
    socket.socket(socket.AF_INET, 
                  socket.SOCK_STREAM).connect( (self.hostname, self.port))
    self.socket.close()

This works, but it still feels like it might not be optimal...