Is it ok to keep TCP connections alive throughout the serving time?

Question:

I’m making a socket TCP server with python that handles multiple connections simultaneously.
so I defined a dictionary to hold the clients socket addresses, so I could access them and traffic the information between the clients easily. but I wander if there is a better way to connect them together without holding for example a hundred connection at the same time, which is really close to keep-alive in http connections that I believe we shouldn’t use excessively and throughout the connection time. so do you guys have any ideas?

That’s who the code looks like:

def run(self, server, port):
    while True:
        server.listen(5)
        conn, addr = server.accept()
        self.connectionMap[str(conn.getpeername())] = conn
        print('New connection:', conn.getpeername())
        Thread_(target=self.manageIndividual, args=([conn, addr, port]))
Asked By: atiya khodari

||

Answers:

There’s nothing wrong with keeping 100 connections open, especially if they are mostly idle.

In the past, having 100 threads open used to be a problem since (on many operating systems) each thread reserves 1MB of memory. So it was desirable to handle many connections per thread. But memory is plentiful now so it’s still not a problem.

In the past, having 1000 connections open on one thread used to be a problem as well, since there weren’t good ways to do that, but now there is epoll (Linux) and I/O Completion Ports (Windows).

But those are historical problems. Nowadays you can get away with thousands of threads, and there is also no problem handling tens of thousands of connections on one thread.

This answer is necessarily shallow since it’s hard to prove a universal negative. In order to really show why it’s not a bad idea I’d have to know why you think it is, and then disprove that.

Answered By: user253751