WebSocket is a communications protocol, providing two-way interactive communication sessions between a client and the server. With WebSocket, you can send and receive event-driven messages. In this tutorial, we're going to create a socket server using SocketIO to build a simple chat application. SocketIO is a standard library implemented in multiple languages such as Python, JavaScript, Java and etc, which helps us to do that in an easy way. Actually, SocketIO is NOT a WebSocket implementation. Although it indeed uses WebSocket as transport when possible. You can consider the SocketIO as a slight wrapper around the WebSocket API. So, let's start:
The first step to create a chat application is to create a socket server. First of all, get the simple chat app repository using the command below:
If you want to run the application to see how it looks, use:
Note that if you are running it on another machine (VM or a remote server), you must make a build of the react project with the remote IP which is set in the config.json file.
let's have a look into the project structure:
There is a pre-build react application that is serving by Flask. To do that, we have the MANIFEST.in file that defines the included directories:
The "main.py" is the entry point of the project which is using the “app.py” to start the socket server:
The flask_app variable is defined in the “globals.py” and the react build folder has been used for the static and the template paths:
In this way, The Flask app can serve the react project too, but before that, we must define a route to return the index.html which is in the app.py:
And finally, we defined the socket events in the socketio.py:
As you see, there is only the "send_message" event which sends back the client message to himself/herself again.
Now, it turns to create the React application which is talked about in the following link: How to create a chat application in React