#StackBounty: #python #multithreading #sockets #python-multithreading Python closing socket and connection in a threaded server?

Bounty: 50

We have a Python socket threaded server example. It is a slightly modified version from
https://stackoverflow.com/a/23828265/2008247. The example works and my tests confirm that it performs better than the blocking server.

But in the example, the socket and the connection objects are not closed. Both objects have close() method. (The close method on a connection is called only on Exception. I would expect it to be called for each connection when it ends.) Do we not need to somehow call them? If so, how?

#!/usr/bin/env python

import socket
import threading

class ThreadedServer():

    def __init__(self, host, port):

        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):


        while True:

            con, address = self.sock.accept()
                             args=(con, address)).start()

    def listenToClient(self, con, address):

        while True:
                data = con.recv(1024)
                if data:
                    # Set the response to echo back the recieved data
                    response = data
                    raise Exception('Client disconnected')
                return False

def main():

    ThreadedServer('', 8001).listen()

if __name__ == "__main__":

Get this bounty!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.