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.
Top comments (7)
Hey man. I think you copied twice the server code in the client 1 code.
Awesome post btw
Thanks ! I'll change it
Shameless plug: I did it once with Unix Sockets in C++
sidvishnoi / socket-chat
CLI Chat app using Unix sockets in Python and C++
Chat server and client with CLI using UNIX networking sockets
(Done as a part of extended class assignments)
See the C++ version
See the Python version.
I think you have not saved your current program file. Your code is fine. It's AsyncServer not asyncServer. :)
No problem. What's your python version?
Sure :)
Hmmm. I just tried with python 3.6. It's working fine.
What command did you use to install socketio?