Look for in our Blog. You will find multiple applications, solutions, code examples. Navigate using the tag cloud or search using specific criteria

TCP Server on Touchberry Pi 3 with Node.js

Introduction

On this post it showed how to implement a TCP server on Touchberry Pi 3


Requirements

Panel PC:      Panel PC 

 

Description

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 tcpServerExample

 

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

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

#!/usr/bin/env node

const TCP_PORT = 5566; 
// Reference: https://nodejs.org/dist/latest-v6.x/docs/api/net.html
var net = require('net');

net.createServer(client => {
	console.log('Connection established with ' + client.remoteAddress); // Works as a print on terminal

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

	client.on('error', err => { // when client got an error execute the next line
		console.log('Connection error ' + err);
	});

	client.on('data', data => { // when client send some data execute the next line
		console.log('Received data: ' + data); // Works as a print on terminal
		try {
			client.write(data); // send the same data as a replay
			console.log('Data replied');
		} catch (e) { 
			console.error('Send error: ' + e); // Print the actual error
		}
	});
}).listen(TCP_PORT); // All this command is to create the server listening on port 5566 with the described function.

 

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

cd tcpServerExample

 

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

node server.js