Http and Https Server with Node JS and Socket.io

Behind this barbaric title, you will find below an example of a web server under linux with Node JS which allows:

  • access in http: port 80
  • access in https: port 443
  • an express-based web server for simple pages
  • permanent and fast access between client and server using socket.io to send a stream of bytes

Node JS Installation

Switch to root:

sudo su

Download version 16 or more recent of Node JS then launch the installation.

curl -sL https://deb.nodesource.com/setup_16.x | bash -
apt-get install -y nodejs

For a first installation to create a project, you need several additional modules to manage web pages and network communications. Create a mkdir…. project folder and do in that folder.

npm install
npm install html
npm install https
npm install express
npm install jquery
npm install socket.io
npm install fs

Generation of a security certificate

Open SSL must be installed on your system. It allows the installation of a self-signed security certificate in order to access your site in https. Run the following command:

openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout selfsigned.key -out selfsigned.crt

In the project launch file with node, here MyServer.js, you need the following lines:

const express = require('express');
const app = express();
app.use(express.static(__dirname + '/public/'));
app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist'));
app.use('/socket.io', express.static(__dirname + '/node_modules/socket.io/client-dist'));

const http = require('http');
const https = require('https');
const net = require('net');
const fs = require('fs');
const Conf = require('./remsdr_modules/configuration.js')
    const {
    Server
} = require("socket.io");
//HTTP Server
const httpserver = http.createServer(app);
const io = new Server(httpserver);
httpserver.listen(80);
//HTTPS Server
const options = {
    key: fs.readFileSync('selfsigned.key'),
    cert: fs.readFileSync('selfsigned.crt')
};
const https_Server = https.createServer(options, app).listen(443);
const ioS = new Server(https_Server);


io.on("connection", (socket) => {
    ServersReceived(socket);
});
ioS.on("connection", (socket) => {
    ServersReceived(socket);
});

function ServersReceived(socket) {
    socket.on("Hello", (arg, callback) => {
        console.log(arg); // "Hello Server"
        callback("Thanks,got it");
    });
    socket.on("News", (data, callback) => {
        console.log(data, data.N);
        callback("Received News from:" + data.U + " at :" + new Date().toLocaleString());
    });
    socket.on("BigData_Bytes", (user, data) => {
        console.log(user, data.length);
    });
}

console.log('Server on port 80 in http and port 443 in https.CTRL+C to quit.');

This double server, http and https is simply launched with the command:

node MyServer.js

In a ‘public’ subfolder of the project folder, we put a simple html page with some javascript to send:

  • news periodically in the form of text etc.
  • 1k byte arrays

The server in return thanks us, by return messages.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client</title>
<script  src="/jquery/jquery.min.js" ></script>
<script src="/socket.io/socket.io.js"></script>
<script>
</script>
</head>
<body>
<h4>Message from server</h4>
<div id="messageFromServer"></div>
</body>
<script>
//User name.  Random pseudo
var User="";
for (i=0;i<5;i++){
	User +=String.fromCharCode(Math.floor(65+63*Math.random()));
}
socket = io();
socket.on("connect", () => {
  console.log(socket.connected); // true
  $("#messageFromServer").html("Connected to Server")
});
socket.on("disconnect", () => {
  socket.connect();
});
socket.emit("Hello", "Hello Server", (response) => {
  console.log(response); // Thanks,got it
});
function emission(){
	var tableauType = new Uint8Array(1000);
    for (var i = 0; i < 1000; i++) {
        tableauType[i] = i % 250;	
    }
	socket.emit("BigData_Bytes", User,tableauType);
}
setInterval(emission , 500);
function news(){	
	console.log("Client news to Server")
	socket.emit("News", {U:User,N:"The news from a client"}, (response)=>{ 
	    console.log(response); 
		$("#messageFromServer").html(response)
	});
}
setInterval(news , 5000);
</script>
</html>

The purpose of this example is to help create exchanges in the form of permanent data stream between several clients and a web server.

F1ATB André

Ham Radio - Home automation - Photovoltaic

You may also like...