NodeJS By .Net Platform

What is Nodejs?

Nodejs is an open source, real time communication, cross platform, server side language which is written by Javascript on Google's v8 Javascript engine. Also Nodejs is enabled to event-driven architecture for asynchronous I/O which can optimize throughput and scalability on our application.

For  a better understanding of Nodejs, it is better to expand the real meaning of the above expressions.

nodejs

Real Time Communication

Real time web solutions are web technologies which enable clients to achieve and receive information as soon as they are published by their authors instead of checking by software or refreshing pages by users manually whether there is new data to expose or not.

Cross Platform

Cross platform means that Nodejs is almost independent from platform and is enabled to be installed on every machine with different operating systems such as Windows, Linux, Macintosh. So Nodejs does not need specific preparation and it is portable.

Server Side Application

There are situations where it is not possible to give all responsibilities to the client due to the fact that the client does not have the ability to accept them. For instance, if we want to store data on a database or do some special processing on a program we need to put these kind of functionalities on the server which is remote from the client and the client can try to achieve their purpose.

Event Driven Architecture

If we are working with some data management systems which have many nodes with different statuses, event driven enables us to find out other statuses very quickly so we are able to respond properly. Think about real estate trading, where houses are for sale or rent and customers want to be aware which house is still available. As soon as a house is selected and is sold its status should be changed for others.

Asynchronous I/O

There are two approaches for I/O, the simple way is synchronous which blocks resources and progress until communication is completed which causes waiting and wastes a lot of resources especially if we have too many I/O.

Another way is asynchronous, which allows critical operations to do their job while waiting for I/O

Throughput

In such a scenario which we need to send and receive messages, there are possibilities that some messages cannot reach the stations so the rate of successful messages which are received correctly on one channel is called throughput.

Scalability

Scalability is a capability of an application that can grow by encountering large scenarios such as large amounts of data or nodes. So unexpected increase of quantity will not decrease quality of system.

Communication Protocols

  1. WebSocket

    Websocket is a full duplex protocol and uses http handshaking internally and allows stream of messages yto flow on top of TCP. It supports: Google Chrome (> 16) Fire Fox (> 11) IE (> 10) Win IIS (>8.0). Due to encrypting message and full duplexes, websocket is the best solution and at first signalR checks both web server and client server whether they support websocket or not.

    Simplex Communication

    It spreads in one way where one point just broadcasts while another point just listens without sending a message, such as television and radio.

    Half duplex

    One point sends a message and in this moment another point cannot send a message and should wait until the first point finishes its transmission and then send its message, it is just for one communication line at a time, such as old wireless devices like walkie-talkies and HTTP protocol.
    Half duplex
    Full duplex

    Both points can send and receive messages at the same time simultaneously, there is no need to wait until the other point finishes its transmission,  such as telephones and websocket protocols.

    Full Duplex

    Full duplex
  2. Server Sent Events (SSE)

    The next choice for SignalR is a server sent event, because of persistent communication between server and client. In this approach, communication does not disconnect and the last data from the server will update automatically and transmit to client via HTTP connection. EventSource is part of HTML5 technology.
     Server Sent Events (SSE)

    Hide Copy Code
    1. var evsrc = new EventSource("url");  
    2.        // Load and Register Event Handler for Messages in this section  
    3.   
    4.        evsrc.addEventListener("message"function (event) {  
    5.            //processing data in this section  
    6.        });  
  3. Forever Frame

    When client sends a request to server, then server sends a hidden iframe as chunked blocks to the client so this iframe is responsible to keep a connection between the client and server forever. Whenever the server changes data, then send data as script tag to client (hidden iframe) and these scripts will be received sequentially.

    Forever Frame
  4. Polling

    Client sends request to server and server responds immediately but after that, server disconnects, so again for establishing communication between server and client, we should wait for the next request from client. To solve this problem, we have to set timeout manually and every 10 seconds the client sends requests to server to check new modification in server side and gets last update data. Polling uses resources and it is not an economic solution.Polling

  5. Long Polling

    Client sends request to server and server responds immediately and this connection remains until a specific time and during this period clients do not have to send explicit requests to server; while in polling, client has to send an explicit request to server during timeout. Comet programming covers this concept.
    Long Polling
  6. Socket.io

    Socket.io is event driven and real time communication which has been abstracted from the five above technologies including websocket, forever frame and long pooling, in a single API and allows application to send and receive data without worrying. [5]

How to code Nodejs by the aid of Microsoft .Net,

  1. Install Visual Studio 2015 , update 3 From Here
  2. Install NodeJS From here.
  3. Install NodeJS Tools for Visual Studio From Here
  4. Install Socket.io From npm
  5. Write code on server
  6. Write code on client
  7. Test it by opening multiple browsers

Install NodeJS

  1. Go to https://nodejs.org/en/
  2. If you are using Windows select "v4.4.7 LTS Recommended For Most Users"

    v4.4.7 LTS Recommended For Most Users

  3. Then Go to Download Folder and run setup file as below picture,

    Download Folder
  4. Select "Next"

    Next

  5. There are different features and you can change them or keep them unchanged and press "Next",

    Next

Install NodeJS Tools for Visual Studio

  1. Before you install NTVS, Go to "Visual Studio" and "Create New Project" -> "Templates" -> "JavaScript" -> There is NO NodeJS,

    JavaScript

  2. Go to https://nodejstools.codeplex.com/releases/view/614706

    Download

  3. Go to Download folder and run setup file,

    Download

  4. Finish Installing "Node.js Tools For Visual Studio" process,

    Node.js Tools For Visual Studio

  5. Now -> Visual Studio -> Create Project -> Templates -> JavaScript -> Node.js

    Node.js

  6. You also will have "npm" Nodejs Package Manager, by which you will be able to install necessary libraries. 

    npm

Install Socket.io

  • In solution right click on "npm" and select "Install New npm Packages"

    Install New npm Packages

How to use Code
Code

Write code on Server.js,

  1. var http = require("http");  
  2. var url = require('url');  
  3. var fs = require('fs');  
  4. var io = require('socket.io');  
  5. var port = process.env.port || 1337;  
  6. var server = http.createServer(function(request, response) {  
  7.     var path = url.parse(request.url).pathname;  
  8.     switch (path) {  
  9.         case '/':  
  10.             response.writeHead(200, {  
  11.                 'Content-Type''text/html'  
  12.             });  
  13.             response.write('hello world');  
  14.             response.end();  
  15.             break;  
  16.         case '/Index.html':  
  17.             fs.readFile(__dirname + path, function(error, data) {  
  18.                 if (error) {  
  19.                     response.writeHead(404);  
  20.                     response.write("page doesn't exist - 404");  
  21.                     response.end();  
  22.                 } else {  
  23.                     response.writeHead(200, {  
  24.                         "Content-Type""text/html"  
  25.                     });  
  26.                     response.write(data, "utf8");  
  27.                     response.end();  
  28.                 }  
  29.             });  
  30.             break;  
  31.         default:  
  32.             response.writeHead(404);  
  33.             response.write("page this doesn't exist - 404");  
  34.             response.end();  
  35.             break;  
  36.     }  
  37. });  
  38. server.listen(port);    
  39. var listener = io.listen(server);  
  40. listener.sockets.on('connection'function(socket) {  
  41.     //Send Data From Server To Client  
  42.     socket.emit('message', {  
  43.         'message''Hello this message is from Server'  
  44.     });  
  45.     //Receive Data From Client  
  46.     socket.on('client_data'function(data) {  
  47.         socket.emit('message', {  
  48.             'message': data.letter  
  49.         });  
  50.         socket.broadcast.emit('message', {  
  51.             'message': data.letter  
  52.         });  
  53.         process.stdout.write(data.letter);  
  54.         console.log(data.letter);  
  55.     });  
  56. });  
Write code on Index.html,
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>  
  2.   
  3. <script src="/socket.io/socket.io.js"></script>  
  4.   
  5. <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>  
  6.   
  7. <script src="http://localhost:8080/server.js"></script>  
  8.   
  9. <script src="/server.js"></script>  
  10.   
  11. <script>  
  12.   
  13. var socket = io.connect();  
  14.   
  15. socket.on('message', function (data) {  
  16.   
  17. $('#conversation').append('</br>' + data.message);  
  18.   
  19. });  
  20.   
  21.    
  22.   
  23. $(document).ready(function () {  
  24.   
  25. $('#send').click(function () {  
  26.   
  27. var msg = $('#text').val();  
  28.   
  29. socket.emit('client_data', { 'letter': msg });  
  30.   
  31. })  
  32.   
  33. });  
  34.   
  35. </script>  
  36.   
  37. <input id="text" />  
  38.   
  39. <button id="send">send</button>  
  40.   
  41. <div id="conversation">This is our conversation</div>  
How to use and run nodejs with .net , 
  1. Press F5 as it runs all web applications on .net and you will see,

    application
  2. Open multi browser and change url to "http://localhost:1337/Index.html", type your message on text box and press button "send" , you will see as soon as you press send, you can see it on the other client.

     other client

Reference

  1. Node.js Tutorial With Socket.io
  2. Node.js
  3. agent.sockets
  4. Real Time Web Solution for Chat by MVC SignalR Hub
  5. Understanding Socket.IO
  6. Pictorial Step-by-step discussion of Nodejs tools for Visual Studio
  7. Socket.io

Feedback

You are most welcome to vote and give your opinion to enhance the quality of my article. So please do not hesitate to leave a comment.

Up Next
    Ebook Download
    View all
    Learn
    View all