Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Royalone94/612c4757243fe341cd5889647760e4cb to your computer and use it in GitHub Desktop.
Save Royalone94/612c4757243fe341cd5889647760e4cb to your computer and use it in GitHub Desktop.
Full socket.io client and server example

Full socket.io client and server example

To see a full explanation, read my answer on SO here: https://stackoverflow.com/a/24232050/778272.

How to use

Create a folder, run npm init -f on it and paste both server.js and client.js there (see files below). Needless to say, you must have Node.js installed on your system.

Install the required libraries:

npm install socket.io
npm install socket.io-client

Run the server:

node server

Open other terminal windows and spawn as many clients as you want by running:

node client
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:8000");
ioClient.on("seq-num", (msg) => console.info(msg));
const
io = require("socket.io"),
server = io.listen(8000);
let
sequenceNumberByClient = new Map();
// event fired every time a new client connects:
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
// initialize this client's sequence number
sequenceNumberByClient.set(socket, 1);
// when socket disconnects, remove it from the list:
socket.on("disconnect", () => {
sequenceNumberByClient.delete(socket);
console.info(`Client gone [id=${socket.id}]`);
});
});
// sends each client its current sequence number
setInterval(() => {
for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
client.emit("seq-num", sequenceNumber);
sequenceNumberByClient.set(client, sequenceNumber + 1);
}
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment