Establishing a successful communication between two or more devices is always a great joy. While I was working on a project I needed to satisfy some requirements. Like, to group certain devices and make communication only between them (chat rooms or group chat). For chatting applications obviously we need a socket protocol. So python has this awesome library called socket.io. This is a python implementation of Nodejs Socket.io.
So the basic idea is to create a server that handles the client messages and delivers to the targeted client. We'll create a aiohttp server which is asynchronous and solves many problems.
Before we start creating a server. Let's set up the python environment.
The python version which I am using is 3.7.9
Now we're good to go.
Let's setup the server first.
What's basically going on here is, we just take an aiohttp server and attach it to a socket-io object. Where there will be a connection upgrade and much more. Let's not get too deep into that. We can also see that every function has a
@sio.event decorator. It just helps in executing the respective function according to the emitted event.
Now run the server with the command
After running it should look something like this.
http://0.0.0.0:8080 represents the default route. So that every machine or device on this local network can access the server.
That's it. The server part is done. Now let's move on to creating clients.
Before running clients know your IP Address in Linux it's
ifconfig in windows it's
Client codes is shown below.
So we created 2 clients with names
Iron man who belong to the same room called
Here the communication happens only in
Marvel room. If
Iron man are in different rooms the communication is not possible.
So let's test it.
When client codes are executed we can see that server logs the name of clients that are connected.
That's it. You can start typing in the terminal itself and hit enter to send.