Bootstrap FreeKB - NodeJS - Getting Started with Client Server on Linux
NodeJS - Getting Started with Client Server on Linux

Updated:   |  NodeJS articles

Let's use the which command to determine if the NodeJS node CLI is in your $PATH. If not, check out my article Install NodeJS on Linux.

~]$ which node
/usr/bin/node

 

Before creating a Client / Server NodeJS app, let's create a simple stand alone "Hello World" app. Create a file named app.js that contains the following console.log.

console.log("Hello World");

 

Use the node CLI to run app.js and "Hello World" should be displayed.

~]$ node app.js
Hello World

 

So far, so good!

Now let's create two apps, the NodeJS client app that will connect to the NodeJS server app.

 

Let's create server.js with the following markup.

const net = require("net");
const server = net.createServer();
const timestamp = () => `[${new Date().toUTCString()}]`
const port = 12345
const host = "127.0.0.1"

server.on("connection", (socket) => {
    console.log(`${timestamp()} successfully connected to server.js`)
})

server.listen(port, host, () => {
    console.log(`${timestamp()} server listening for connections at ${host}:${port}`);
})

 

Let's start server.js.

~]# node server.js
[Sat, 23 Mar 2024 03:56:40 GMT] server listening for connections at 127.0.0.1:12345

 

Open a second SSH connection to the same Linux system that server.js is on and let's create client.js with the following markup.

const net = require('net');
const timestamp = () => `[${new Date().toUTCString()}]`
const port = 12345
const host = "127.0.0.1"

const client = net.createConnection({host: host, port: port},() => {
    console.log(`${timestamp()} successfully connected to server.js`);
})

 

Let's run client.js. Perfect! The client is connected to server.js. Awesome.

~]$ node client.js
[Sat, 23 Mar 2024 03:57:39 GMT] successfully connected to server.js

 

Let's say firewalld is running on your Linux system.

~]$ sudo systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
     Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2023-07-24 02:40:19 CDT; 7 months 29 days ago

 

Let's update firewalld to allow connections on port 12345. I did not use the --permanent flag because I don't want this to be a permanent change to firewalld since port 12345 is just the port I'm using for testing purposes.

~]$ sudo firewall-cmd --add-port=12345/tcp
success
~]$ sudo firewall-cmd --list-port
12345/tcp

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 5e7851 in the box below so that we can be sure you are a human.