EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask WebSocket
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask WebSocket

Flask WebSocket

Introduction to Flask WebSocket

Flask WebSocket is defined as a communication protocol that is used in networking across a client-server architecture. The client-server architecture is a distributed application structure that enables the distribution of work or partition tasks across the servers, the provider of resource or service, and clients which requests service. It is on the same grounds on how HTTPS works, but just a few advantages of using WebSocket that makes it a useful technique to be used over HTTPS. This communication protocol is widely used in the gaming industry which is played on servers or websites which needs to output a result with the lowest latency. Here we will see the syntax that is required from a Flask perspective and the working of WebSocket in Flask.

Syntax of Flask WebSocket

A web application that requires low latency and developed over Flask requires the skill of using WebSocket efficiently, and for the efficient and standardized methodology, we have extensions that cater to the needs of the hour. Here we will see about extensions of WebSocket in a flask from the syntax perspective so that when we see working of WebSocket in Flask, it is easier to map it back with the syntax.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

1. Installing flask socketio module in the python environment.

pip install flask-socketio

2. Calling the module of socketio in python.

from flask_socketio import SocketIO

3. Instantiating the socketio using the application instance.

socketInstance = SocketIO(< Flask application instance >)
  • < Flask application instance > needs to be replaced with the instance of the Flask application that will be declared as a part of the code.

4. RequirementsWebSock.txt

    • Flask
    • Flask-Login
    • Flask-Session
    • Flask_SocketIO
    • itsdangerous
    • Jinja2
    • MarkupSafe
    • python-engineio
    • python-socketio
    • six
  • Werkzeug

5. Installing all the requirements from the above requirements.txt file.

pip install requirementsWebSock.txt

How WebSocket Works in Flask?

A WebSocket ensures the continuous connection between the client and the server. Hence, it becomes more important than it provides a bi-directional communication channel that can operate over HTTP and use a single TCP/IP socket connection. Here we will see about the working of WebSocket and understand how the protocol facilitates the passing of message between the client and the server to ensure that “persistent” communication is the duty WebSocket is assigned with.

It is very important to understand the question “Why WebSocket”. The reason we emphasize on the question “why” will ensure a better understanding of the working of WebSocket when we go through that in detail and also enable you to connect the working with the final place of it getting used. The limitations of HTTP technology gave rise to the idea of WebSocket. Since HTTP is a unidirectional protocol, the client should first request the data, and only then can the data be sent to the server. Now in case if the server needs to continuously send data, it needs to request for the same every time.

The workaround for this short coming was to use the concept of long polling, where in the HTTP request is made with a longer time timeout period. But the disadvantage is that the resources are held up even when there is no data left to send. So now for working of WebSocket, the message-based data is allowed to be sent using UDP and uses HTTP as the initial mechanism for transferring and keeps the TCP connection alive after an HTTP response is sent so that the connection can be used for sending message between client and server. This method allows the “real-time” application development without going through the hassle of long polling concept.

The workflow followed in general for WebSocket working is:

  • The WebSocket object is first initialized in the code by importing the required module. For uniformity and the sake of focusing on a single module, we will be keeping SocketIO as the instance, which will be explained in this article. Once the object is instantiated, this object will act as a server for Flask-SocketIO development in Werkzeug by using the command socketio.run. The client now receives a page provided by the application to load the socket.io library, and the connection is established.
  • With the establishment of connection, messages are received as events. The handlers are registered for these events with a similar use case of how routes are handled by view function. In parallel to receive of messages, the handlers defined above are capable of sending messages as well.
  • Now that send and receive is all set, the Broadcasting of messages appears to be another feature of SocketIO, which is used to send message to all the clients that are connected.

There are some additional features like rooms (used for sending messages to grouped user), connection events (sending messages during connection and disconnection events) etc. which are advanced level uses of WebSocket.

Examples of Flask WebSocket

Given below are the examples of Flask WebSocket:

Example #1

Installing flask socketio module in the python environment.

Syntax:

pip install flask-socketio

Output:

Flask WebSocket 1

Example #2

Calling the module of socketio in python.

Syntax:

from flask_socketio import SocketIO
SocketIO

Output:

Calling the module of socketio

Example #3

Simple flask application with WebSocket.

Syntax:

Message.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tutorial on Flask: A Web socket example</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// sending a connect request to the server.
var socket = io.connect('http://localhost:5000');
socket.emit('after connect', function(connectMsg) {
$('#log').append('<br>' + $('<div/>').text('What is the intention of the code: ' + connectMsg.data).html());
});
});
</script>
</head>
</head>
<body>
<h1>Example on SocketIO : EduCBA</h1>
<h2>Message Received:</h2>
<div id="log"></div>
</body>
</html>

Python File:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
appFlask = Flask(__name__)
socketio = SocketIO(appFlask)
@appFlask.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def test_connect():
socketio.emit('after connect', {'data':'Let us learn Web Socket in Flask'})
if __name__ == '__main__':
socketio.run(appFlask)

Output:

Flask WebSocket 3

Conclusion

In conclusion, in this article, we have seen about working of WebSocket and following it is a small piece of code that tries to replicate the same concept. Try changing the code and with restarting the Flask application to reload the website. To surprise, nothing will change.

Recommended Articles

This is a guide to Flask WebSocket. Here we discuss the introduction, how WebSocket works in flask? And examples, respectively. You may also have a look at the following articles to learn more –

  1. Flask jsonify
  2. Flask Migrate
  3. Flask Template
  4. Flask Users
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more