0
0
Node.jsframework~5 mins

Socket.io overview in Node.js

Choose your learning style9 modes available
Introduction

Socket.io helps your app talk instantly between the browser and server. It makes real-time communication easy and fast.

You want to build a chat app where messages appear instantly.
You need live updates on a dashboard without refreshing the page.
You want multiplayer games where players see each other's moves right away.
You want to notify users immediately when something important happens.
You want to sync data live between many users connected to your app.
Syntax
Node.js
const io = require('socket.io')(server);
io.on('connection', (socket) => {
  socket.on('eventName', (data) => {
    // handle event
  });
  socket.emit('eventName', data);
});

Use io.on('connection') to listen when a user connects.

Use socket.on to listen for messages from that user.

Examples
This logs when a user connects to the server.
Node.js
io.on('connection', (socket) => {
  console.log('User connected');
});
This listens for a 'chat message' event from the user and logs the message.
Node.js
socket.on('chat message', (msg) => {
  console.log('Message:', msg);
});
This sends a 'welcome' event with a message to the connected user.
Node.js
socket.emit('welcome', 'Hello user!');
Sample Program

This is a simple chat server using Socket.io. When a user connects, it welcomes them. When a user sends a message, it broadcasts to all users.

Node.js
import { createServer } from 'http';
import { Server } from 'socket.io';

const httpServer = createServer();
const io = new Server(httpServer, { cors: { origin: '*' } });

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  socket.on('chat message', (msg) => {
    console.log('Received message:', msg);
    io.emit('chat message', msg); // send to all clients
  });

  socket.emit('welcome', 'Welcome to Socket.io chat!');
});

httpServer.listen(3000, () => {
  console.log('Server listening on port 3000');
});
OutputSuccess
Important Notes

Socket.io works with WebSocket but falls back to other methods if needed.

Remember to handle CORS if your client and server run on different origins.

Use io.emit to send messages to all connected users.

Summary

Socket.io makes real-time communication between browser and server simple.

It listens for connections and events, then sends messages instantly.

Great for chat apps, live updates, and multiplayer games.