Dhanush
Posted on January 30, 2020
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
It is recommended to use python-3.6.+
Install the following libraries
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 python server.py
After running it should look something like this.
The URL 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 ipconfig
.
Client codes is shown below.
Client 1
Client 2
So we created 2 clients with names Deadpool
and Iron man
who belong to the same room called Marvel
.
Here the communication happens only in Marvel
room. If Deadpool
and 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.
Posted on January 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 13, 2024