Last updated: 2021-02-21, tested with socket.io v3.1.1
This is the simplest implementation you will find for a client/server WebSockets architecture using socket.io.
To see a full explanation, read my answer on SO here: https://stackoverflow.com/a/24232050/778272.
If you're looking for examples using frameworks, check these links:
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 [email protected]
npm install [email protected]
Run the server:
node server
Open other terminal windows and spawn as many clients as you want by running:
node client
If one is only keeping track of users, using rooms seems like a nice suggestion indeed.
In the example above, however, I also keep a state for each user (their current sequence number). I did this to illustrate how one would store data for each user.
Regarding your mention of the use of global variables: in my example, the Map variable is only visible within the module. It could also be easily turned into an instance member by encapsulating the login within a class (which I would probably do if the logic got more involved).