SocketIo Overview
socket.io enable realtime, bidirectional communication for Nodejs
Backend
We use Express as backend framework.
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
<script src="/socket.io/socket.io.js"></script>
- connect in your frontend script file
const clientSocket = io();
Function
Receive -> on()
socket.on('<head>', (data) => {
// deal with data
});
Send -> emit()
socket.emit('<head>', data);
Send to all client socket except itself -> socket.broadcast.emit()
socket.broadcast.emit('<head>', data);
Sent to all client socket include itself -> io.emit()
io.emit('<head>', data);
Group socket together
socket.join('<name>');
Send to a group
socket.to('<name>').emit();
socket.broadcast.to('<name>').emit();
io.to('<name>').emit();