nats-message-channel
Implementation of NATS MQ with websocket protocol.
Scenario
Let's say we want to send real-time notifications/messages to our users without using any 3rd party service like Socket IO or Pusher.
And of course we want to separate it from our backend server to scale it freely.
Our implementation scenario will be as follows;
-
Step 1: Of course, there should be an authentication process. When users first load the page, they send a message to our Websocket server with their own tokens.
-
Step 2: Our Websocket server send these credentials to the authentication channel (via req/reply method) on the NATS server.
-
Step 3: Our backend server has subscribed to the authentication channel. It performs the authentication process according to the incoming message.
-
Step 4: Once authentication is successful, our Websocket server marks this connection as authed and allows it to subscribe to the user-specific notification channel on the NATS server.
-
Step 5: When an event occurs (eg. order received), our backend server sends this notification to the user-specific notification channel on NATS server.
-
Step 6: Our websocket server receives the notification message through the NATS server and sends it to the user as real-time.
Our websocket server is written in NodeJS.
Suppose that our backend project is written in PHP. At that case our publisher and subscriber will be written in PHP.
Installation
First of all, you should install to NATS server.
Go to /websocket folder and run ;
npm installGo to /api folder and run;
composer installUsage
We need to run our Websocket server and Auth Subscriber.
- Go to
/apifolder and run;
node app.js- For authentication, we run our authentication subscriber in our backend.
Go to
/apifolder and run;
php authSubscriber.php- Open
/client/user1.htmlfile on web browser then click thesubscribebutton.
Now you can send a notification to the user-specific notification channels that the user is subscribed.
For example;
- Go to
/apiand run this command ( first argument is user id, second is message );
php notificationPublisher.php 1 hello!A screenshot of the processes in the background. You can follow the life cycle from the descriptions on terminal;
Summary
You can adapt it to your own project, inspired by the architecture in this project.
License
MIT ยฉ Samet Sahindogan

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

