Implement a WebSocket Using Flask and Socket-IO(Python)

Learn how to compose the client-server interface utilizing Websocket technology with Flask and Socket-IO modules available in python

Narendra Harny
The Startup
6 min readAug 17, 2020

--

WebSocket

WebSocket is a communication protocol for the client-server model.
So for understanding WebSocket, It is batter to compare the WebSocket specialty over HTTPS.
There are a few advantages of WebSocket over HTTPS that is what the specialty of WebSocket.
So If we have to decide that we should choose the WebSocket for our applications then we can analyze the requirements as per the below-written features of WebSocket.

HTTP carries extra overheard in individual request and response, WebSocket carries the overhead data while placing connection then it carries less or balanced data within individual request-response.

Difference HTTP vs WebSocket

Note: For full-duplex Bi-directional client-server communication the WebSocket is the best choice.

The WebSocket’s can be implemented with all server-side technologies, I am using Flask and Socket-IO modules from Python.
Please understand the steps below to implement the WebSocket using Flask and Socket-IO

Step1: Creating a project and creating requirements.txt

  • First of all, will start by setting up the virtual environment for our sample project.
  1. Create a project folder.
  2. Create a requirments.txt file into the project folder.
  3. Add below code into requirments.txt.

Note: the above dependency is required for implementing a web socket so we will install all for creating the virtual environment.

Step2: Creating a virtual environment and install all required modules from python.

  • Now create a virtual environment “VENV” for the project.
create a virtual environment
  • Go to project root folder and open terminal/cmd and execute the below commands

$ virtualenv <envname>:

envname” can be anything I have used “websocketenv”

  • Activate the virtual env now(Execute the activate.bat file present location)

$ {Project Root path}/websocketenv/Scripts/activate.bat

  • Now install the requirements.txt using the command

$ pip install requirements.txt

The current project structure looks like this. for me.

Current project structure

Step3: We will design a simple program for understanding the functionality of a WebSocket.

  • Create a Python file named app.py in the project root folder.
  • Add the below code into the app.py

Note: First We are creating a client GUI web page for implementing the WebSocket basic feature of a running WebSocket.

app.py

  • Now create the templates directory into the project root folder and create one index.html file in the templates directory.
  • Add the below code into index.html

index.html

Now we can test the WebSocket by running “app.py”

The expected console output will be after running app.py

WebSocket console output

Now run the URL: http://localhost:5000/ into a web browser and you will see the message “This is WebSocket Client” on the web page.

**127.0.0.1 — — [2020–08–17 10:09:07] “GET / HTTP/1.1” 200 260 0.004024**

If the WebSocket connection is established then the above request log will be added in the console logs whenever the web page will get refreshed.

Flask, render_template
flask_socketio , SocketIO

we have used the following modules for implementing the basic socket but it is not showcasing anything like how socket works so, let’s extend the feature and implement the sending message and receiving from one client to another.

Final Step: We will implement a message passing from one client to another client in this step.

The current project structure is like this:

Current Project structure

The final code for app.py and index.html

app.py

index.html

After adding the final code please start the WebSocket server by running app.py and now again we can check the output in the web browser.

Output web page socket server
  • Here we have implemented two kinds of message one is “Send Message” that’s is a normal ping msg and Send Broadcast Message which is sending or broadcasting the data over a socket connection.
  • We have a couple of options to check the functionality but if we run socket on localhost then it's difficult to observe the feature.

Make your localhost accessible anywhere.

We can use the “NGROK” tool and we can easily make localhost servers accessible anywhere.

One the localhost is set up according to the above link, you can use the generated HTTP or HTTPs URLs instead of the localhost and You can test a Socket server like a live hosted server and use it as a simple chat broadcast server.

Can open the link into your phone and see the message sharing in between. Or use another computer and test exchanging messages.

Please explore the code one by one and here I have given some explanations about few must-know things from source code.

we were given the Flask app instance (standard initialization)
we were not given the app, but we were given a message_queue (standard initialization for the auxiliary process), will call init_app from an app factory function.

A decorator that is used to register a view function for a given URL rule.

A Decorator to register a SocketIO event handler. This decorator must be applied to SocketIO event handlers.

This small application can be extended for any features please do have use of it freely.

Thanks, Programmers

Happy Coding!

--

--

Narendra Harny
The Startup

Connect on https://medium.com/make-android | Write On, Android AOSP & Applications | Python | DevOps | Java | C++ | Kotlin | Shell | Linux | Android Auto | IVI