Are you interested in building a real-time chat application? Flask-SocketIO is a great tool for building interactive web applications that require real-time communication. In this tutorial, we will show you how to create a simple chat application using Flask-SocketIO.
What is Flask-SocketIO?
Flask-SocketIO is an extension for Flask that adds support for WebSocket communication. It provides a simple and easy-to-use API for building real-time web applications. With Flask-SocketIO, you can create applications that require real-time communication between the client and the server.
Setting Up the Environment
Before we get started, make sure you have the following installed:
- Python 3
- Flask
- Flask-SocketIO
You can install Flask and Flask-SocketIO using pip. Open up your terminal and run the following command:
pip install flask flask-socketio
Creating the Flask Application
First, let's create a Flask application that will serve as the backend for our chat application. Create a file called app.py and add the following code:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app)
Here, we are creating a Flask application and initializing a SocketIO instance with it. We also set a secret key for the application, which is used to encrypt session cookies.
Next, we define a route for the homepage of our application. We will create this template in the next section. Finally, we start the SocketIO server by calling the run method.
Creating the HTML Template
Now, let's create an HTML template for our application. Create a file called templates/index.html and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Flask-SocketIO Chat App</title>
<script src="https://cdn.socket.io/4.1.2/socket.io.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://localhost:5000');
socket.on('connect', function() {
console.log('Connected!');
});
});
</script>
</head>
<body>
<h1>Flask-SocketIO Chat App</h1>
</body>
</html>
Here, we are creating a basic HTML template that includes the SocketIO and jQuery libraries. We also create a script that connects to the SocketIO server and logs a message to the console when the connection is established.
Adding Chat Functionality
Now, let's add chat functionality to our application. Update app.py with the following code:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(message):
print('received message: ' + message)
emit('message', message, broadcast=True)
if __name__ == '__main__':
socketio.run(app)
Here, we define a SocketIO event handler for the 'message' event. When a client sends a message to the server, the handle_message function is called. We print the message to the console and then broadcast the message to all connected clients using the emit method.
Next, let's update our HTML template to include a form for sending messages. Update templates/index.html with the following code:
<!DOCTYPE html>
<html>
<head>
<title>Flask-SocketIO Chat App</title>
<script src="https://cdn.socket.io/4.1.2/socket.io.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://localhost:5000');
socket.on('connect', function() {
console.log('Connected!');
});
$('form').submit(function(event) {
event.preventDefault();
socket.send($('#message').val());
$('#message').val('');
});
socket.on('message', function(message) {
$('#messages').append($('<li>').text(message));
});
});
</script>
</head>
<body>
<h1>Flask-SocketIO Chat App</h1>
<ul id="messages"></ul>
<form>
<input id="message" type="text" autocomplete="off">
<button>Send</button>
</form>
</body>
</html>
Here, we add a form that allows the user to enter a message and send it to the server. When the form is submitted, we use the send method to send the message to the server. We also clear the input field after sending the message.
We also define a SocketIO event handler for the 'message' event. When the server sends a message, the append method is used to add the message to the list of messages on the page.
Running the Application
Now that our application is complete, let's run it! Open up your terminal and navigate to the directory where app.py is located. Run the following command:
python app.py
This will start the Flask development server and the SocketIO server. Open up a web browser and navigate to http://localhost:5000. You should see the chat application.
Conclusion
In this tutorial, we showed you how to create a simple chat application using Flask-SocketIO. We covered the basics of Flask-SocketIO and demonstrated how to use it to build real-time web applications. With Flask-SocketIO, you can create powerful and interactive web applications that provide a seamless user experience.