0
0
Expressframework~5 mins

Why real-time matters in Express

Choose your learning style9 modes available
Introduction

Real-time means your app can send and receive information instantly. This makes users feel connected and up-to-date without waiting.

Chat apps where messages appear immediately
Live sports scores updating as the game plays
Online games where players interact instantly
Stock market apps showing price changes live
Collaborative tools like shared documents updating for all users
Syntax
Express
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('message', (msg) => {
    io.emit('message', msg);
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

This example uses socket.io with Express to handle real-time events.

io.on('connection') listens for new users connecting.

Examples
This listens for a 'chat message' event and sends it to all users immediately.
Express
io.on('connection', (socket) => {
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });
});
Sends a message only to the connected user as a welcome.
Express
socket.emit('welcome', 'Hello!');
Sends an update to all connected users at once.
Express
io.emit('update', { score: 10 });
Sample Program

This Express app uses Socket.io to send and receive messages instantly. When a user connects, they get a welcome message. When they send a chat message, everyone sees it right away.

Express
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.get('/', (req, res) => {
  res.send('<h1>Real-time demo</h1>');
});

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.emit('welcome', 'Welcome to real-time app!');

  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
OutputSuccess
Important Notes

Real-time apps keep users engaged by showing updates immediately.

Socket.io works well with Express to add real-time features easily.

Remember to handle user disconnects to keep your app stable.

Summary

Real-time means instant updates between users and server.

Use real-time for chat, live scores, games, and collaboration.

Express with Socket.io is a simple way to add real-time features.