I'm trying to write a chatroom in this post, using the socket package in Python.
The general structure of this problem can be devided into three parts. In the simplest case we have two clients, namely client0 and client1, and a server. Except for that the server provides the interface, everything else will remain the same among these three classes: they inherit from the class socket.socket and have two methods sending and recving. The two methods are built to loop infinitely just so that all requests are accepted unattended. In the meantime, in order to avoid interruption between these two functions, we have to run them simultaneously using the threading package. The two clients are reporting to different ports of the same host and the server listens to both, also in an infinite loop.
if __name__ == '__main__': c = Client(1) c.start()
Start server.py first and then the two clients. The terminal screenshot is as below.
Again, this is just a very simple, toy-like chatroom and there're a lot to be implemented if you want to, like quiting schemes, front-end delivery and broadcasting in multi-client cases. However, I'm sure taking this as the starting point won't hurt. Enjoy coding!
1.You can also resort to more advanced ones like socketserver or something else. They may be convenient, but also sometimes redundant. ↩︎