What is Node?

*This tutorial was designed to work with a Raspberry Pi running Jessie but should work on other platforms.

 

Node.js is a very efficient and popular way to manage and create web applications.  This tutorial walks you through how to set up a node server.  A sever is a computer that can take and process requests from clients (a client is a computer connected to a server). 

 

Servers can do many things including:

·       Pass information between two or more clients.

·       Store large amounts of information that clients can access.

·       Give clients control over the server’s hardware. (The GPIO on the Pi)

 

For more information check out www.nodejs.org.   There are huge communities of developers that use Node.js to do amazing things.  Google it!

I also found this blog post very helpful: danielnill.com/nodejs-tutorial-with-socketio/  You should read it.

 

Before you go on…

Make sure Node.js and socket.io are installed.

 

Node Check:

To check if Node is installed open a terminal window and type in node –v.  This should display the current version or an error, in which case you will need to install node first.

 

If you need to install node try these instructions: http://joshondesign.com/2013/10/23/noderpi

 

Socket.io check:

1.   Open a terminal window

2.   Run node in interactive mode by just typing node

3.   Type require(‘socket.io’)

If you get an error that says “Cannot find module” it is not installed.

 

This will install socket.io for you npm install socket.io

 

 

 

Setting up the Server

The server itself is a JavaScript file that will be run by Node.  It will accomplish a few things for us:

 

1.     It will listen for potential clients on a specified port.

2.     Our clients will be requesting an html page, the server will send the client the right one.

3.     The server will send and receive messages from the client using the socket connection.

4.     The server will handle any errors that might come up.

 

Step 1: Setting up Folders and Files

-         Make a new folder in the Public directory called  simpleServer.  Save your files in here.

-         Make one empty file called simpleServer.js

-         Make one empty file called socket.html

 

Step 2: The server

 

This code will get a basic server up and running for you:

Paste it into simpleServer.js and save.

/***************************************************

Node Server:

Save this file in the same directory as an html file called socket.html.

You can handle as many cases as you like you will need to add a new case for each one in the switch.

 

***************************************************/

 

 

//Files the server needs

var http = require('http');

var url =require('url');

var fs = require ('fs');

var io = require('socket.io');

 

//Start the server:

//You shouldn’t need to change much in here unless

//you are adding more pages to link to

 

var server=http.createServer(function(request,response){

var path = url.parse(request.url).pathname;

     

      switch(path){ // Check which file was requested

 

            case '/':  //If no html page is requested

                  response.writeHead(200, {'content-tpe':'text/html'});

                  response.write('Welcome to My Server!');

                  response.end();

                  break;

 

            case'/socket.html': //if socket.html is requested

                  fs.readFile(__dirname + path, function(error, data){

                        if(error){

                              response.writeHead(404);

                              response.write("opps that page does not exist");

                              response.end();  

                        }

                        else{

                              response.writeHead(200, {'content-tpe':'text/html'});

                              response.write(data,"utf8");

                              response.end();

                        }

 

                  });

            break;

      default:

            response.writeHead(404);

            response.write("opps that don't exist bro");

            response.end();

            break;

      }

});

 

//Spcify which port you will be listening to.

server.listen(8001);

console.log("Server is running");

 

 

 

//Create the socket connection

var listener = io.listen(server);

listener.sockets.on('connection',function(socket){

      console.log('Connected');

 

//Send a message to the client

      socket.emit('message',{'message': 'Sever Says Hi'});

 

 

//Get a message from the client

      socket.on('client_data',function(data){

           

 

            if(data=='sayHi'){ //Do something depending on the message contents

 

                  console.log('The client says hi ');

                 

 

            }

      });

           

});

 

Important Notes:

 

1.  Run the server from the terminal window like this:

 

node simpleServer.js

 

2. Access the server from another computer using the server computer’s IP address and the port something like this:

 

198.123.8.196:8001 (If it is working it should say “Welcome to my Server”

 

Or to access socket.html:

 

 198.123.8.196:8001/socket.html

 

You can find your ip address using the ifconfig tool in the terminal.

 

3. socket.emit()  sends a message to the client.

 

socket.on() receives a message from the client.

 

Step 3: The Client

Socket.html is the web page that will be given to the client computer.  It will establish the socket connection and handle all user interactions.  (Buttons, messages, various user input etc)

 

Save this in the same folder as simpleServer.js, call it socket.html

<html>

 

<head>

<!-- Add the socket.io.js script to this page -->

 

<script src="/socket.io/socket.io.js"></script>

</head>

 

<body>

 

<script>

 

var socket = io.connect(); //establish the socket connection

 

socket.on('message', function(data){ //Handle incoming messages from the server

document.getElementById("messages").innerHTML=data.message;

});

 

function hiFunction(){

 

socket.emit('client_data','sayHi');//send a message to the sever

 

document.getElementById("messages").innerHTML="Mesage sent";

 

}

</script>

 

 

<button onclick="hiFunction()" type="button">Say Hi to Sever</button>

 

<p id="messages"></p>

 

</body>

</html>

Socket Communication:

 

Socket communication works more or less the same in the client and the server.  There are two “callback: methods:

 

socket.emit( ) sends data

 

socket .on ( ) receives data 

 

For more good description on how this works check out this post.

 

 

 

Test your system by trying to access it from am iPad or phone on the guest network. Make sure you get messages working both ways. If you are having trouble….

1.     Make sure you have the right IP address and Socket.

2.     Make sure both computers are on the same network.

3.     Use console.log() in strategic places to help you see what is happening.

4.     Test your html page on its own to make sure it works properly.