In this tutorial, we will explore how to create a WebSocket using Flask-SocketIO on the backend. WebSockets provide a full-duplex communication channel between a client and a server, allowing real-time data transfer. They are commonly used in interactive web applications, chat applications, and online gaming.
Prerequisites
Before we begin, make sure you have the following installed:
- Python 3.x
- Flask
- Flask-SocketIO
To learn how to setup a flask project, refer to our guide on - Creating a virtual environment in Python - https://blog.pythonicit.com/articles/7 .
Setting up the Flask-SocketIO Server
First, let's set up the Flask-SocketIO server. Create a new Python file, for example, app.py, and import the necessary modules:
from flask import Flask, render_template
from flask_socketio import SocketIO
Next, create a Flask app and initialize the SocketIO extension:
app = Flask(__name__)
socketio = SocketIO(app)
Now, let's define a route to serve the HTML file that will establish the WebSocket connection:
@app.route('/')
def index():
return render_template('index.html')
Finally, run the server:
if __name__ == '__main__':
socketio.run(app, debug=True)
Setting up the Frontend
Create an HTML file named index.html in the templates folder of your Flask project. Add the following code to establish the WebSocket connection:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log('Connected to the server');
});
</script>
</head>
<body>
<h1>WebSocket Example</h1>
</body>
</html>
Testing the WebSocket Connection
Start the Flask server by running python app.py in your terminal. Open a web browser and navigate to http://localhost:5000. You should see the message "Connected to the server" in the browser console, indicating that the WebSocket connection has been successfully established.
Conclusion
In this tutorial, we learned how to create a WebSocket using Flask-SocketIO. WebSockets provide a powerful mechanism for real-time communication between clients and servers, enabling interactive and responsive web applications.