You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Socket.IO is a library that enables real-time, bidirectional, and event-driven communication between a client and a server. It is built on top of the WebSocket protocol, which allows for fast and simultaneous communication between the server and the browser. Socket.IO provides additional features like fallback options for HTTP long-polling and automatic reconnection, enhancing the reliability and versatility of real-time applications.
1. Real-time communication: Socket.IO enables instantaneous and bidirectional data exchange between web clients and servers, eliminating the need for page refreshes.
19
+
20
+
2. Event-driven: Socket.IO operates on an event-driven model, allowing clients and servers to communicate by sending and receiving events. This simplifies the development of complex real-time applications.
21
+
22
+
3. Reliability: Socket.IO ensures a reliable connection, even in the presence of network disruptions. It automatically attempts to reconnect if the connection is lost.
23
+
24
+
4. Scalability: Socket.IO is designed to handle a large number of concurrent connections, making it scalable for applications with high traffic.
25
+
26
+
Socket.IO finds application in various scenarios, including:
27
+
28
+
1. Chat applications: Socket.IO is commonly employed for creating chat apps, enabling real-time communication between users.
29
+
30
+
2. Multiplayer games: Socket.IO facilitates real-time player interactions and synchronization, making it suitable for building multiplayer games.
31
+
32
+
3. Live streaming applications: Socket.IO can be utilized to construct live streaming platforms, enabling users to watch live streams in real-time.
33
+
34
+
If you're looking to develop real-time web applications, Socket.IO is an excellent choice. It offers simplicity, reliability, and efficiency, and is well-supported across different browsers and devices.
35
+
36
+
37
+
## Using Socket.IO with Flask
38
+
To use Socket.IO with Flask, we will utilize the `flask-socketio` package. In this tutorial, we will demonstrate how Socket.IO can update a card on a Flask dashboard. We will utilize the Flask dashboard called [Flask-gradient-able](https://github.com/app-generator/flask-gradient-able).
* Run the flask application to ensure it is properly setup using the command
64
+
```bash
65
+
(venv) sample-flask-socketio$ flask run
66
+
```
67
+
* Visit [`http://127.0.0.1:5000`](http://127.0.0.1:5000) on your browser.
68
+
69
+
* Create an account to view the homepage of the application. You can stop the flask server using `Ctrl + c`.
70
+
71
+
### Integrating Socket.IO with flask
72
+
To integrate Socket.IO into a Flask application, we will utilize the `flask-socketio` package. This package empowers Flask applications to harness the capabilities and advantages of SocketIO.
73
+
74
+
* Install `flask-socketio` package using the command
* Create a file in the `apps` folder named `events.py`, this file will be used to create the socketio object and will also contain events that will be handled using socketio
80
+
```py
81
+
# apps/events.py
82
+
83
+
from flask_socketio import SocketIO,
84
+
85
+
socketio = SocketIO()
86
+
87
+
@socketio.on('connect')
88
+
defconnect_event():
89
+
print('Client connected')
90
+
```
91
+
92
+
* Add Socket.IO to the application by making the following changes to `apps/__init__.py`
93
+
```
94
+
# apps/__init__.py
95
+
...
96
+
from apps.events import socketio
97
+
...
98
+
def create_app(config):
99
+
app = Flask(__name__)
100
+
...
101
+
socketio.init_app(app)
102
+
return app
103
+
```
104
+
105
+
To ensure that the events to be handled by SocketIO are loaded into the `socketio` object and registered with the Flask app, we import `socketio` from `app/events.py` and initialize it with the Flask app using `socketio.init_app(app)`. This ensures that the event handlers are properly integrated with the SocketIO functionality.
106
+
107
+
* Make the following changes to `run.py`
108
+
```py
109
+
# run.py
110
+
...
111
+
from apps import socketio # <-- NEW
112
+
...
113
+
114
+
if__name__=="__main__":
115
+
socketio.run(app) # <-- UPDATED
116
+
```
117
+
118
+
* Add SocketIO script tag to `apps/templates/home/index.html`, this loads the Socket.IO library and establishes a connection.
To ensure that a connection can be established by your application:
135
+
1. run the flask app using `flask run` from your terminal.
136
+
2. Open `http://127.0.0.1:5000` on your browser.
137
+
3. Log in to the application
138
+
4. Open the developers console using `Ctrl + Shift + I` or `Command + Option + i` (on Mac).
139
+
140
+
### Emitting and receiving events between client and server
141
+
SocketIO sends messages as events, allowing for communication between the server and client in both directions. The server can send events to the client, and vice versa. SocketIO includes default events such as `connect` and `message`, but we can create custom events and handle them on both the client and server-side.
142
+
143
+
Next, we will be sending a message from the client to the server and then we will print that message on the terminal.
144
+
145
+
* Make the following change to `apps/templates/home/base.html`
146
+
```html
147
+
<!-- apps/templates/home/index.html -->
148
+
...
149
+
<scripttype="text/javascript"charset="utf-8">
150
+
constsocket=io();
151
+
socket.on('connect', function(data) {
152
+
console.log('Socket.IO is connected!!!')
153
+
});
154
+
socket.send('The send method is used to initiate the message event');
155
+
</script>
156
+
```
157
+
158
+
* Add the following line of code to `apps/events.py`
159
+
```py
160
+
# apps/events.py
161
+
...
162
+
@socketio.on('message')
163
+
defhandle_message(data):
164
+
print('This is a message:', data)
165
+
```
166
+
Refresh your browser and check your Python terminal. You will observe that the message from the client is printed on the Python terminal.
167
+
168
+
#### Creating custom events
169
+
In addition to having default events, we can create custom events to tailor our code to various situations. The key distinction between messages and custom events lies in how they are triggered. To trigger a custom event, we utilize the `emit` method, as we will see shortly.
170
+
171
+
* Create a custom event called `new event` by adding the code below to `apps/events.py`
172
+
```py
173
+
# apps/events.py
174
+
...
175
+
@socketio.on('new event')
176
+
defhandle_new_event(data):
177
+
print('A new event was emitted from the client containing the following payload', data)
178
+
socketio.emit('server event', {'data': 'This is how you trigger a custom event from the server-side'})
179
+
```
180
+
181
+
* Add the code below to `apps/templates/home/index.html` to receive and send events from the client side
182
+
```html
183
+
<!-- apps/templates/home/index.html -->
184
+
<scripttype="text/javascript"charset="utf-8">
185
+
...
186
+
socket.emit('new event', 'The data can be an object or a string');
187
+
188
+
socket.on('server event', function(data) {
189
+
console.log(data);
190
+
});
191
+
</script>
192
+
```
193
+
After making the changes to the code as mentioned, please refresh your browser and examine both your browser console and the Python terminal. You will observe the events being handled by both sides of the application.
194
+
195
+
## Real-time Updates in Flask
196
+
Using SocketIO, we will implement real-time updates in our Flask application. The details of a card on our dashboard will be updated whenever a new entry is added to our database.
197
+
198
+
* First we will be creating a `Sales` table using schema. Create a new file in `apps/home` named `model.py` and add the following code
199
+
```py
200
+
# apps/home/model.py
201
+
from apps import db
202
+
203
+
classSales(db.Model):
204
+
205
+
__tablename__ ='Sales'
206
+
207
+
id= db.Column(db.Integer, primary_key=True)
208
+
product = db.Column(db.String(64))
209
+
amount = db.Column(db.String(64))
210
+
status = db.Column(db.Enum('Completed', 'Not Completed'), default='Not Completed')
211
+
212
+
def__init__(self, **kwargs):
213
+
for key, value in kwargs.items():
214
+
setattr(self, key, value)
215
+
216
+
def__repr__(self):
217
+
returnstr(self.product)
218
+
219
+
defsave(self):
220
+
db.session.add(self)
221
+
db.session.commit()
222
+
```
223
+
224
+
* Make the following update to `apps/__init__.py` so the new `Sales` table can be created when the flask server starts up.
225
+
```py
226
+
# apps/__init__.py
227
+
...
228
+
defregister_extensions(app):
229
+
from apps.home.model import Sales # <--- NEW
230
+
db.init_app(app)
231
+
...
232
+
```
233
+
Please restart the Flask server and visit the homepage. This action will result in the addition of the `Sales` table to the database.
234
+
235
+
### Implementing real-time updates using Socket.IO
236
+
To implement real-time updates on the application, we will create a new route that allows the addition of entries to the database. Once an entry is added, we will update the card components on the homepage.
237
+
238
+
* We will be creating a route for adding new entries to the `Sales` table. Add the code below to `apps/home/routes.py`
Now that we have a route that can add products to the sales database, we emit a `sales` event that is broadcasted to all clients connected to the server.
264
+
265
+
While the Flask server is running, open another terminal and execute the following command to add entries to your database using the route:
266
+
267
+
```bash
268
+
curl -X POST -F product=product-name -F amount=product-amount -F status=Completed http://localhost:5000/sales
269
+
```
270
+
**NOTE:** You can replace `product-name` with the value you want to add to the database, and `product-amount` with whatever number you choose. `-F status=Completed` can be removed to create an entry with a status of `Not Completed`.
271
+
272
+
* Let's add the following line of code to apps/templates/home/index.html to listen for the sales event emitted from the route we created earlier
273
+
```html
274
+
<!-- apps/templates/home/index.html -->
275
+
...
276
+
<scripttype="text/javascript"charset="utf-8">
277
+
...
278
+
socket.on('sales', function(data) {
279
+
// function to be carried out when the event is emitted will go here
280
+
console.log(data);
281
+
});
282
+
</script>
283
+
```
284
+
You can try adding entries to your database using the command mentioned earlier. Upon checking your browser console, you will observe that the data sent using `curl` is displayed in the console.
285
+
286
+
### Updating a card or component on the Flask dashboard in response to events
287
+
For the final part of our tutorial on using SocketIO to achieve real-time updates in our application, we will write the logic to update the `Orders received` card on the homepage.
288
+
289
+
* Let's make the following changes to `app/home/routes.py` to add a context that sends the numver of sales and sales completed to the homepage. These values will be used to update the `Orders received` card:
**NOTE** Take note of the added `id` attribute inside the `span` tags
314
+
315
+
* Now let's write the logic to update the cards when a POST request is sent to `http://localhost:5000/sales`. We'll make the following changes to `apps/templates/home/index.html`
When the server emits the `sales` event, it triggers the function responsible for updating the card elements on the homepage. This function is automatically executed in response to the event and is responsible for handling the necessary updates to the card components based on the received data.
332
+
333
+
## Conclusion
334
+
In this tutorial, we learned how to use Socket.IO with Flask to create real-time updates in web applications. We started by setting up a simple Flask application, and then we integrated Socket.IO with Flask. We then learned how to emit and receive events between the client and server. Finally, we implemented real-time updates using Socket.IO, and we updated a card or component on the Flask dashboard in response to events.
16
335
17
-
<br />
336
+
This tutorial has shown how easy it is to use Socket.IO with Flask to create real-time updates in web applications. Socket.IO is a powerful tool that can be used to create a variety of real-time applications, such as chat applications, multiplayer games, and stock tickers.
18
337
19
338
## Resources
20
339
21
340
- 👉 Free [Support](https://appseed.us/support/) via Email & Discord
22
341
- 👉 [Custom Development Services](https://appseed.us/custom-development/) provided by experts
0 commit comments