How Sockets Work (Backend)
1. What is a Socket?
A socket is an endpoint for communication between two machines over a network. In the backend,
sockets are typically used to handle real-time communication, such as chat apps, live notifications,
or streaming data.
2. How Backend Sockets Work
- The backend server creates a socket and binds it to a specific port. - It listens for incoming
connections. - When a client connects, the server accepts the connection and establishes a
two-way communication channel. - The server can then send and receive messages in real-time.
3. Example (Node.js + Socket.IO)
```js 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) => { console.log('message: ' + msg); io.emit('message', msg); }); });
server.listen(3000, () => console.log('Server running on port 3000')); ```
4. Key Points
- Backend sockets handle multiple clients. - They support event-based communication. - Useful for
scalable real-time applications.