This website uses Google Analytics and Advertising cookies, used to generate statistical data on how visitors uses this website (with IP anonymization) and to deliver personalized ads based on user prior visits to this website or other websites. [read more]
These cookies are disabled by default until your Accept/Reject Consent.
The Consent can be changed at any time by accesing the ePrivacy button located at the bottom of every page. Enjoy your visit!



NGINX, Apache and NodeJS socket.io, all in harmony

You already know about the NodeJS and all his goodies. But you're a PHP web developer and is not easy for you to make the complete switch. Or maybe you don't want.
So why not to get all goodies from all sides?
timeline Now you can easily build the required NGINX, Apache, PHP and NodeJS stack using the WebH-NL - a professional web hosting solution for self managed servers.
Just to remember some used by me:
- Real-time communications between client browser and server;
- number of connected users;
- list of authenticated users;
- instant webpage updates without user interaction or frenetic ajax requests;
- lightweight chats;
- free push messaging using GCM (Google Cloud Messaging);
- instant alerts;
- screenshots for webpages;
- emailing (SMTP, SendGrid);
- Real-time notifications from PostgreSQL pg_notify triggers

And the list can continue, especially for things that can't be made easily (or at all, or without hammering the servers) only in native PHP combined only with client side JavaScript.

Designed by Freepik
To got access to all NodeJS goodies, you will need two simple rules for your example.com NGINX server block.

Putting all servers in harmony

Just add this lines to the example.com NGINX server block:
### NodeJS upstreams (part of the http, outside the server block)
# socket.io connections
upstream io_nodes {
   ip_hash;
   server 127.0.0.1:9000;
}

server {
   ....
   # you may put above the SSL part from: http://www.b247.eu.org/2017/03/hight-quality-free-https-encryption-for.html   
   
   ...
   # you may put above the location block for static files: https://www.b247.eu.org/2017/03/an-easy-way-to-prevent-execution-of.html
   
   #Proxy pass the root location access to the Apache Web server
   location / {
      proxy_pass http://127.0.0.1:8080;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
   }
   
   #NodeJS Applications
   location /nodeapp/ {
      access_log off;
      proxy_pass http://io_nodes/;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
   }
}
check this for a comprehensive NGINX server block example:
https://github.com/b247/WebH-NL/blob/master/files/vhosts/fqdn-nginx-ssl.conf
I already done this, now what?
Now it's time to establish the connection between the webpage and the NodeJS apps.

Remember, the NodeJS applications are server side javascripts and must be placed outside the public_html folder, so no public access there. If you have a structure like example.com/public_html then for NodeJS apps I'll recommend to use example.com/my-nodejs-server-scripts for your server side NodeJS JavaScript application.

Your first NodeJS application with socket.io real-time communication embedded.

From your shell:
Navigate to example.com/my-nodejs-server-scripts and then install your first NodeJS module, socket.io
npm install socket.io

Depending of your needs, there are NodeJS modules for a lot of things, but for real-time communication between Apache webpage and the NodeJS application server, socket.io is all that we need.

Create a file named app.js (in the example.com/my-nodejs-server-scripts  location). This file will  be your first NodeJS application:

/*server side libraries*/
var io = require('socket.io').listen(9000);
   io.set("origins", "https://www.example.com:*");
When executed, a socket.io server will start on port 9000, waiting for connections.

Client side JavaScript (the public_html scripts area):

/*client side libraries*/
<script src="jslibs/vendor/socket.io.min.js" type="text/javascript"></script>
<script src="jslibs/socket.js?v=1" type="text/javascript"></script>
socket.io.min.js can be downloaded from Github or even be uses from a CDN location
socket.js will be created by us
In the socket.js file we will instantiate the communication with our server side app.js:
$(function() {
   var socket = io.connect('wss://www.example.com', {path: '/nodeapp/socket.io'})
 
})

Start the app.js (node app.js) and we will have real-time communication established between client side script and the server side script. If all goes well, it's all about you in how do you intend to use this feature, but don't worry, I'll provide a simple case usage at the bottom of this article.
Meanwhile, we need to make sure that our app.js server application will run forever, even if we reboot the server, and even if we make code changes to the app.js script.

Run Node JS application forever

Open the shell and navigate to example.com/nodeapp, remember? the place where we installed the socket.io and we created the app.js script.
Then, we will install, guess what? the forever NodeJS module :)
npm install forever

and start the app.js forever
killall -9 NodeJS ; forever stop app.js ; forever start -a -l $(pwd)/forever.log --minUptime 1000  --spinSleepTime 1000 -w --watchDirectory $(pwd) --watchIgnore *.log  --watchIgnore node_modules app.js

What about server reboots? Use the crontab for this (sudo crontab -e), add this line to , and you are done.
#NodeJS/app.js start at booting/startup
@reboot              killall -9 NodeJS ; cd /path/to/example.com/nodeapp ; forever stop app.js ; forever start -a -l $(pwd)/forever.log --minUptime 1000  --spinSleepTime 1000 -w --watchDirectory $(pwd) --watchIgnore *.log  --watchIgnore node_modules app.js

That's all, I know that you have the skills to use your scripts at the best.
But as I promised above, here you will find two scripts (the client side and the server side) that demonstrate the NodeJS socket.io real-time communication capabilities.

Right now: Website total opened pages, client side JavaScript (socket.js)

$(function() {
   var socket = io.connect('wss://www.example.com', {path: '/nodeapp/socket.io'})
   
   socket.on('now online', function(data){
      console.log(data)
   })
   socket.on('visited pages', function(data){
      console.log(data)
   })
   socket.on('connected', function (data) { 
      socket.emit('visited page', {connection_url: window.window.location.href});
   })
}) 

Right now: Website total opened pages, server side JavaScript (app.js)

var io = require('socket.io').listen(9000);
   io.set("origins", "https://www.example.com:*");

var connections = 0;
var extended_connections = {};
io.sockets.on('connect', function(socket) {
   connections++;
 
   socket.emit('connected', { connected: true });
   
   socket.on('visited page', function(data) {
      extended_connections[data.connection_url] = parseInt(extended_connections[data.connection_url]||0) +1;
      socket.once('disconnect', function () {
         extended_connections[data.connection_url] = parseInt(extended_connections[data.connection_url]||0) -1;
         if (parseInt(extended_connections[data.connection_url]||0)<1) {
            delete extended_connections[data.connection_url];
            connections--;
         }
         io.emit('visited pages', extended_connections);
         io.emit('now online',connections);
      })
      io.emit('visited pages', extended_connections);
      io.emit('now online',connections);
   });
});

Wish you well.

label_outline

Share this post on your favorite networks.
© Copyright 2017 b247.eu.org | Just another information technology blog - All Rights Reserved