Just Learn Code

Building a Real-Time Chat Application with Flask WebSocket

Introduction to Flask WebSocket and Real-Time Chat Application

The internet has revolutionized the way we communicate with each other. Nowadays, people can connect with each other from different parts of the world in real-time.

One of the technologies that have enabled this real-time communication is WebSocket. WebSocket is a protocol that enables bidirectional communication between the client and the server in real-time.

In this article, we will explore WebSocket and how to build a real-time chat application using Flask and the flask_socketio module.

Overview of building a chat app using Flask and flask_socketio module

Flask is a lightweight web application framework that enables developers to build web applications quickly and easily. Flask provides an easy-to-use API for building web applications with Python.

Flask’s simplicity and flexibility have made it a popular choice for building web applications. To enable real-time communication in Flask, we will use the flask_socketio module.

The flask_socketio module provides support for WebSocket and other real-time communication protocols. Using the flask_socketio module, we can easily add real-time communication capabilities to our Flask applications.

In this article, we will build a real-time chat application using Flask and the flask_socketio module. The chat application will enable users to send and receive messages in real-time.

Server-Side Implementation using Flask

Installation of flask_socketio module

Before we can use the flask_socketio module in our Flask application, we need to install it. We can install the flask_socketio module using pip, the Python package manager.

To install the flask_socketio module, we can use the following command:

“`

pip install flask-socketio

“`

Initialization of SocketIO() class object

After installing the flask_socketio module, we need to initialize the SocketIO() class object in our Flask application. We can initialize the SocketIO() class object by importing it from the flask_socketio module and instantiating it with the Flask application object.

We can use the following code to initialize the SocketIO() class object:

“`

from flask import Flask

from flask_socketio import SocketIO

app = Flask(__name__)

socketio = SocketIO(app)

“`

Definition of route and function for receiving and broadcasting messages

After initializing the SocketIO() class object, we can define the route and function for receiving and broadcasting messages. We can use the @socketio.on() decorator to define the route for receiving and broadcasting messages.

The route for receiving and broadcasting messages should be the same. Using the same route for receiving and broadcasting messages simplifies our code and makes it easier to manage.

We can use the following code to define the route and function for receiving and broadcasting messages:

“`

@socketio.on(‘message’)

def handle_message(message):

print(‘Received message: ‘ + message)

socketio.emit(‘message’, message)

“`

In the above code, we define the route for receiving and broadcasting messages using the @socketio.on() decorator. The route is ‘message’.

The function ‘handle_message’ receives the message and broadcasts it using the socketio.emit() method. The method socketio.emit() broadcasts the message to all clients connected to the server.

Execution of Flask app using socketio.run()

After defining the route and function for receiving and broadcasting messages, we can execute our Flask app using the socketio.run() method. The socketio.run() method starts the Flask app with the real-time communication capabilities provided by the flask_socketio module.

We can use the following code to execute our Flask app using the socketio.run() method:

“`

if __name__ == ‘__main__’:

socketio.run(app)

“`

In the above code, we check if the name of the current module is ‘__main__’. If it is, we execute the socketio.run() method with the Flask app object.

Conclusion

In this article, we explored WebSocket and how to build a real-time chat application using Flask and the flask_socketio module. We covered the installation of the flask_socketio module, initialization of the SocketIO() class object, definition of the route and function for receiving and broadcasting messages, and execution of the Flask app using the socketio.run() method.

With this knowledge, you can explore other real-time communication protocols and build powerful real-time web applications using Flask.

Client-Side Implementation using HTML and JavaScript

Now that we have implemented the server-side of our Flask WebSocket real-time chat application, let’s move on to the client-side. In this section, we will cover the implementation of the client-side using HTML and JavaScript.

We will create a user interface that enables users to send and receive messages in real-time. We will be using the socket.io and jQuery scripts to establish the WebSocket connection between the client and the Flask server.

Importing socket.io and jQuery scripts

Before we can use the socket.io and jQuery scripts, we need to import them into our HTML file. We can do this by adding the following script tags to the head section of our HTML file:

“`html

“`

The first script tag imports the socket.io script from the socket.io CDN.

The second script tag imports the jQuery script from the jQuery CDN. We can also download these scripts and serve them locally if we prefer.

Connection to Flask server using socket object

After importing the socket.io script, we need to establish a connection between the client and the Flask server. We can do this by creating a socket object and connecting it to the Flask server.

We can use the following code to create a socket object and connect it to the Flask server:

“`javascript

var socket = io.connect(‘http://’ + document.domain + ‘:’ + location.port);

“`

In the above code, we create a socket object and connect it to the Flask server using the io.connect() method. The method takes the server address as a parameter.

We can use the document.domain and location.port variables to dynamically generate the server address.

Handling of connect event and sending initial message

After connecting to the Flask server, we need to handle the connect event. The connect event occurs when the socket connects to the server.

We can use the following code to handle the connect event and send an initial message:

“`javascript

socket.on(‘connect’, function() {

socket.send(‘User has joined the chat!’);

});

“`

In the above code, we use the socket.on() method to handle the connect event. The function inside the method sends a message to the server using the socket.send() method.

The message is ‘User has joined the chat!’. We can customize this message to suit our needs.

Handling of message event and displaying received messages

After connecting to the Flask server and sending an initial message, we need to handle the message event. The message event occurs when the socket receives a message from the server.

We can use the following code to handle the message event and display received messages:

“`javascript

socket.on(‘message’, function(message) {

var li = $(‘

  • ‘).text(message);

    $(‘#messages’).append(li);

    });

    “`

    In the above code, we use the socket.on() method to handle the message event. The function inside the method creates a list item element using the jQuery $(‘

  • ‘) function and sets its text to the received message using the .text() method.

    We then append the list item to the unordered list element with an ID of ‘messages’ using the .append() method.

    Handling of send button click event and sending message

    After implementing the message receiver, we need to implement the message sender. We can do this by creating an input field for the user to enter their message and a send button to trigger the sending of the message.

    We can use the following HTML code to create the input field and send button:

    “`html

    “`

    In the above code, we create an input element with an ID of ‘message’ and a placeholder text of ‘Enter message…’. We also create a button element with an ID of ‘send’.

    We can use the following JavaScript code to handle the send button click event and send the message:

    “`javascript

    $(‘#send’).click(function() {

    var message = $(‘#message’).val();

    socket.send(message);

    $(‘#message’).val(”);

    });

    “`

    In the above code, we use the jQuery .click() method to handle the send button click event. The function inside the method gets the value of the message input field using the .val() method and sends it to the server using the socket.send() method.

    We then clear the message input field using the .val(”) method.

    Installation of Required Modules

    Before we can use the flask_socketio module in our Flask application or the socket.io and jQuery scripts in our HTML file, we need to install them. We can use the following commands to install the required modules:

    Upgrade of python-socketio module

    We can upgrade the python-socketio module using the following command:

    “`

    pip install –upgrade python-socketio

    “`

    Upgrade of python-engineio module

    We can upgrade the python-engineio module using the following command:

    “`

    pip install –upgrade python-engineio

    “`

    Installation of Flask-SocketIO module

    We can install the Flask-SocketIO module using the following command:

    “`

    pip install Flask-SocketIO

    “`

    Conclusion

    In this article, we covered the implementation of the client-side of our Flask WebSocket real-time chat application using HTML and JavaScript. We imported the socket.io and jQuery scripts, connected to the Flask server using a socket object, handled the connect and message events, and implemented the message sender using a send button.

    We also covered the installation of the required modules for our Flask WebSocket real-time chat application. With these implementation details, you can build powerful and real-time web applications with Flask and WebSocket.

    Complete Python Code

    Now that we have covered the server-side and client-side implementation of our Flask WebSocket real-time chat application, let’s bring them together by providing the complete Python code. In this section, we will provide the complete Python code that includes the modules, socket initialization, message handling, and Flask app execution.

    “`python

    from flask import Flask, render_template

    from flask_socketio import SocketIO, send

    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)

    send(message, broadcast=True)

    if __name__ == ‘__main__’:

    socketio.run(app)

    “`

    In the above code, we import the necessary modules for our Flask WebSocket real-time chat application. We initialize the Flask app and the SocketIO object.

    We define the route for our app and use the @socketio.on() decorator to define the message handler, which prints the received message and broadcasts it to all connected clients.

    Complete HTML Code

    In addition to the complete Python code, we also provide the complete HTML code for our Flask WebSocket real-time chat application. In this section, we will provide the HTML code that includes the input field, send button, and message display area.

    “`html

    Flask WebSocket Real-time Chat Application

      “`

      In the above code, we define the HTML structure of our Flask WebSocket real-time chat application. We import the necessary scripts for implementing the WebSocket connection and message handling.

      We then define the input field, send button, and message display area. We use JavaScript to handle the WebSocket connection, message handling, and sending of messages.

      Conclusion

      In this article, we provided the complete Python and HTML code for our Flask WebSocket real-time chat application. The Python code included the initialization of the Flask app, socket initialization, message handling, and Flask app execution.

      The HTML code included the input field, send button, and message display area, as well as the JavaScript code for handling the WebSocket connection, message handling, and message sending. With this implementation, you can build a powerful and real-time web application with Flask and WebSocket.

      In this article, we explored WebSocket and built a real-time chat application using Flask and the flask_socketio module. We covered the installation of required modules and the server-side implementation using Flask, including initializing the SocketIO() class object, defining the route and function for receiving and broadcasting messages, and executing the Flask app using socketio.run().

      We then moved on to the client-side implementation using HTML and JavaScript, including importing socket.io and jQuery scripts, connecting to the Flask server using a socket object, handling the connect and message events, and implementing the message sender using a send button. We concluded by providing the complete Python and HTML code for the entire chat application.

      The importance of WebSocket technology and the powerful real-time web applications it enables cannot be overstated, and this article provides all the necessary information to start building such applications.

    • Popular Posts