socket.io enable realtime, bidirectional communication for Nodejs
Backend
We use Express as backend framework.
1
2
3
4
5
6
7
8
9
10
11
12
| const express = require('express');
const path = require('path');
const http = require('http');
const socket_io = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socket_io(server);
io.on('connection', (server_socket) => {
// ...
}
|
Frontend
- bring client side socket.io in your html file
1
| <script src="/socket.io/socket.io.js"></script>
|
- connect in your frontend script file
1
| const clientSocket = io();
|
Function
Receive -> on()
1
2
3
| socket.on('<head>', (data) => {
// deal with data
});
|
Send -> emit()
1
| socket.emit('<head>', data);
|
Send to all client socket except itself -> socket.broadcast.emit()
1
| socket.broadcast.emit('<head>', data);
|
Sent to all client socket include itself -> io.emit()
1
| io.emit('<head>', data);
|
Group socket together
Send to a group
1
2
3
| socket.to('<name>').emit();
socket.broadcast.to('<name>').emit();
io.to('<name>').emit();
|