Beware: Experimental technology ahead!
Simply, it is a WebSocket server created in node using express
and ws
modules.
A WebSocket server sends a message that it receives to all of it's connected clients, a thing that we don't want sometimes.
So, we add users into specific rooms and restrict the communication within a room.
A room is a virtual place to which users get added(actually join) based on the room's limit. So, every message you send is only received by users in the same room that you are in.
- Clone the project
- Go to the folder and run
npm install
to install the dependencies - Run
npm start
to start the WebSocket server - Go to
http://localhost:8000
to check if it works
Note: node-ws uses only JSON to move message back and forth. If the message is not in JSON, then it gets dumped.
The number of users in a room can be controlled by changing ROOM_LIMIT
(>=2)
in index.js
.
When a new connection is made to the WebSocket server, the first thing to do after the connection is opened, is to send a join request followed by the name of room you wish to join.
let ws = new WebSocket('ws://localhost:8000');
ws.onopen = () => {
ws.send(JSON.stringify({
type: 'join',
room: 'my-private-room'
}));
};
{
type: 'join | leave | msg | notif',
room: 'my-private-room',
body: 'A private message'
}
When sending requests:
-
type
: Type of request/response.Valid strings:
'join' | 'leave' | 'msg'
'join'
- A join request, used along with 'room''leave'
- Request to leave the room(WebSocket connection is not closed)'msg'
- Just send the messages to other users -
room
: Name of room to joinUsed along with
type: 'join'
only
When receiving responses:
-
type
: Type of response messageValid responses:
'msg' | 'notif'
'msg'
- Specifying a message is received'notif'
- Notification from server(like when users leave room) -
body
: Includes message content
Note: This is just some experimental technology that may not be of any use for you. Use with caution!
Author: ramlmn
License: MIT