Expo & Flask-SocketIO

React-Native frontend and Flask backend.

Beatriz Nakamura Vechiato
2 min readApr 16, 2024

Why Flask-SocketIO

Flask-SocketIO is a library for Flask, a web framework, that integrates WebSocket support into Flask applications. You might need it if

  • Your application requires real-time updates, such as chat applications, online gaming, live sports updates, financial trading platforms, etc.
  • You want the client and server to initiate communication independently, or you need to broadcast messages.

Server-side

Set up

  1. We initialise a Flask application and configure it with a secret key for security.
  2. Enable Cross-Origin Resource Sharing (CORS) to allow communication with clients from different origins.
  3. A SocketIO instance is created and linked to the Flask application, allowing it to handle WebSocket connections.

Event handlers

Allow us to listen to specific requests given in the @socketio.on decorators. When a client sends a message to the server, the corresponding function is triggered.

Implementation

Client-side

Set up — socket.js

  1. Define the URL of the Socket.IO server to which the client will connect.
  2. Create a Socket.IO client instance, which can connect to a Socket.IO server. We export it so other modules or components can use this client instance to send and receive messages to and from the server

Event handlers — App.js

Expo will allow you to build the front end of your application in JavaScript, so add this logic to whichever page in your application communicates with the server. In this case, and the linked GitHub repository, it isApp.js.

We create event listeners for specific events received from the server. They are added to a useEffect hook, as placing them directly within the functional component body would cause them to be re-registered on every render, potentially leading to multiple event listeners being attached unnecessarily.

Further, by returning a cleanup function, we ensure that event listeners are removed to prevent memory leaks and unexpected behaviour.

Implementation

Handles the configuration of your socket
Creates event handlers and renders a simple View

Versions

  • Expo (50.0.1).
  • Flask-SocketIO (4.5.6).

--

--