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 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 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 tcpServerExample
Â
Now all is ready to execute the server.js typing on terminal:
node server.js
TCP Server on Touchberry Pi 3 with Node.js