Python Sockets – How Communication Between Chat Server and Client Works

chatpythonsockets

(Socket programming newbie here…)

So, for learning purposes I've just started developing a chat server and client in Python, and I was wondering how it is usually implemented.

When someone connects to the server, does the socket stay alive until the whole client is closed (All messages are sent through it), or is a new socket created for each new message?

If the second case is true, then what I've imagined by "connection" was always wrong (Since by each message a new connection is made). How does it work?

Best Answer

I don't know how they usually work, but when I implemented one, I chose your first approach and it worked ok. That's also how IRC works, so it can clearly scale to a reasonable number of users.

If you're opening a new socket for each message, there would be a problem in terms of how the server sends messages to the clients, who may be behind firewalls and unable to accept incoming confections. Polling is possible, and I know some early web chat clients did this, but I believe this approach is now very rare.

A third option is using UDP, where the cost of maintaining an open socket is lower (because there's no connection whose state must be maintained). I don't know if any popular chat systems do this, however.

Related Topic