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.
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
- 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.
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
- 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.
Hide Copy Code
- var evsrc = new EventSource("url");
-
-
- evsrc.addEventListener("message", function (event) {
-
- });
- 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.
- 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.
- 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.
- 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,
- Install Visual Studio 2015 , update 3 From Here
- Install NodeJS From here.
- Install NodeJS Tools for Visual Studio From Here
- Install Socket.io From npm
- Write code on server
- Write code on client
- Test it by opening multiple browsers
Install NodeJS
- Go to https://nodejs.org/en/
- If you are using Windows select "v4.4.7 LTS Recommended For Most Users"
- Then Go to Download Folder and run setup file as below picture,
- Select "Next"
- There are different features and you can change them or keep them unchanged and press "Next",
Install NodeJS Tools for Visual Studio
- Before you install NTVS, Go to "Visual Studio" and "Create New Project" -> "Templates" -> "JavaScript" -> There is NO NodeJS,
- Go to https://nodejstools.codeplex.com/releases/view/614706
- Go to Download folder and run setup file,
- Finish Installing "Node.js Tools For Visual Studio" process,
- Now -> Visual Studio -> Create Project -> Templates -> JavaScript -> Node.js
- You also will have "npm" Nodejs Package Manager, by which you will be able to install necessary libraries.
Install Socket.io
- In solution right click on "npm" and select "Install New npm Packages"
How to use Code
Write code on Server.js,
- var http = require("http");
- var url = require('url');
- var fs = require('fs');
- var io = require('socket.io');
- var port = process.env.port || 1337;
- var server = http.createServer(function(request, response) {
- var path = url.parse(request.url).pathname;
- switch (path) {
- case '/':
- response.writeHead(200, {
- 'Content-Type': 'text/html'
- });
- response.write('hello world');
- response.end();
- break;
- case '/Index.html':
- fs.readFile(__dirname + path, function(error, data) {
- if (error) {
- response.writeHead(404);
- response.write("page doesn't exist - 404");
- response.end();
- } else {
- response.writeHead(200, {
- "Content-Type": "text/html"
- });
- response.write(data, "utf8");
- response.end();
- }
- });
- break;
- default:
- response.writeHead(404);
- response.write("page this doesn't exist - 404");
- response.end();
- break;
- }
- });
- server.listen(port);
- var listener = io.listen(server);
- listener.sockets.on('connection', function(socket) {
-
- socket.emit('message', {
- 'message': 'Hello this message is from Server'
- });
-
- socket.on('client_data', function(data) {
- socket.emit('message', {
- 'message': data.letter
- });
- socket.broadcast.emit('message', {
- 'message': data.letter
- });
- process.stdout.write(data.letter);
- console.log(data.letter);
- });
- });
Write code on Index.html,
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
-
- <script src="/socket.io/socket.io.js"></script>
-
- <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
-
- <script src="http://localhost:8080/server.js"></script>
-
- <script src="/server.js"></script>
-
- <script>
-
- var socket = io.connect();
-
- socket.on('message', function (data) {
-
- $('#conversation').append('</br>' + data.message);
-
- });
-
-
-
- $(document).ready(function () {
-
- $('#send').click(function () {
-
- var msg = $('#text').val();
-
- socket.emit('client_data', { 'letter': msg });
-
- })
-
- });
-
- </script>
-
- <input id="text" />
-
- <button id="send">send</button>
-
- <div id="conversation">This is our conversation</div>
How to use and run nodejs with .net ,
- Press F5 as it runs all web applications on .net and you will see,
- 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.
Reference
- Node.js Tutorial With Socket.io
- Node.js
- agent.sockets
- Real Time Web Solution for Chat by MVC SignalR Hub
- Understanding Socket.IO
- Pictorial Step-by-step discussion of Nodejs tools for Visual Studio
- 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.