2nd step to create a TCP client on a Touchberry Pi 3.Creating a TCP Client using Node.js

December 10, 2018 by
2nd step to create a TCP client on a Touchberry Pi 3.Creating a TCP Client using Node.js
Alejandro Jabalquinto

Introduction

This post shows how to implement a TCP client on Touchberry Pi 3.


Requirements 

Panel PC with Linux distribution:       Panel PC


Installation

To get the Node.js JavaScript interpreter we need to install the command cURL on our Linux.

cURL command is very useful for HTTP/S requests. To get the cURL we just need to type on the Linux Terminal:

sudo apt-get install curl

Once there is the cURL installed we can download the node source typing on the terminal: 

curl -sL https://deb.nodesource.com/setup_6.x > setup_node.sh

 

With this cURL command, we save what is on the link with the name of “setup_node.sh”. Next we have to change the permissions of setup_node.sh typing on the terminal: 

chmod 755 setup_node.sh

chmod modifies the permission of the file. With the next line we will execute the file setup_node.sh as a root, this command can take a while.

sudo ./setup_node.sh 

After that we are available to install the node.js typing, this command can time several minutes as well:

sudo apt-get install nodejs

Next, we create a directory to save the Node.js JavaScript server file typing on the terminal: 

mkdir tcpClientExample

Inside of this directory is where this example has been chosen to save the server.js file. 


Example

Next, it is showed the client.js file, there are some comments to get a better understanding of what is going on on every code line:

var net = require('net');

var client = new net.Socket();
 client.connect(1337, '127.0.0.1', function() { // configuration of the connection
       console.log('Connected');
       client.write('Hello, server! Love, Client.');
 });

client.on('data', function(data) {            // when data arrives to the client execute the next line
       console.log('Received: ' + data);
       client.destroy(); // kill client after server's response
 });

client.on('close', function() {               // when client close the connection execute the next line
       console.log('Connection closed');
 });

After saving the server file on tcpServerExample directory follow the next instructions to execute the TCP server. First just go to the tcpServerExample directory typing  on the terminal:

cd tcpClientExample

Now all is ready to execute the server.js typing on terminal:

node client.js


​Search in our Blog

2nd step to create a TCP client on a Touchberry Pi 3.Creating a TCP Client using Node.js
Alejandro Jabalquinto December 10, 2018
Share this post

Looking for your ideal Programmable Logic Controller?

Take a look at this product comparison with other industrial controllers Arduino-based. 

We are comparing inputs, outputs, communications and other features with the ones of the relevant brands.


Industrial PLC comparison >>>