Introduction
Nowadays having real time web applications as two way connection is necessary in all kind of fields. Javascript is a good solution but it just work at client side while there are some scenario which we really need to have solutions which works at server side. For instance storing data on database or processing data at server side. There are two popular technologies one is SignalR and other Node.js.
You can use it by .net from http://www.codeproject.com/Articles/1111793/Node-js-For-Net-Developers-By-WCF
What is Nodejs
Nodejs is an open source, real time communication, cross platform, server side which is written by javascript on Google`s v8 javascript engine. Also Nodejs is enable to event driven architecture for asynchronous I/O which can optimize throughput and scalability on our application.
For have a better understanding of Nodejs, it is better to expand the real meaning of above expressions. [3]
Why we use Node.js?
First and formost is because of we need real time solution for our web application in two way client to server and server to client side, so data can be shared between both sides. Another good advantage is Node.js is cross platform and does not need to complex preperation and installation before using it. It established well for I/O and last but not least the probability of missing data is too rare.
Real Time Communication
Real time web solutions are web technologies which enables client to achieve and receive information as soon as they are published by their authors instead of checking by software or refreshing page by user manually that whether there is new data to expose or not.
Cross Platform
Cross platform means that Nodejs is almost independent from platform and is enable to install 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 that it is not possible to give all of responsiblities to client due to client does not have potential to accept them. For instance, if we want to store data on data base or make some special processing on program we need to put these kind of functionalities on server which is remote from client and client should make try to gain its purpose.
Event Driven Architecture
If we are working with some data management systems which have many nodes with different status so evet driven enable us to find out other status very soon so we are capable to response properly. Assume real state trading where houses are for sale or rent and customers want to be aware which house is still available and they can hit it. As soon as house is selected and is sold so its status should be changed for others i order to avoid to hit again it.
Asynchronous I/O
There are two approaches for I/O, simple way is synchronous which blocks resources and progress until communication is completed which wait and waste a lot of resources specially if we have many I/O.
Other way is asynchronous which allows critical operations do their job during it is waiting for I/O
Throughput
In such a scenario which we need to send and receive messages, there are possibilities that some messages can not be reached to stations so the rate of successful messages which are received correctly on one channel is called throughput.
Scalability
Scalability is a capability of application that can grow by encountering large scenario such as large amount of data or nodes. So unexpected growing from quantity will not decrease quality of system.
Communication Protocols
1. WebSocket
Websocket is a full duplex protocol and uses http handshaking internally and allow stream of messages flow on top of TCP. It supports: Google Chrome (> 16) Fire Fox (> 11) IE (> 10) Win IIS (>8.0). Due to encrypt message and full duplex, 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 just spreads in one way when one point just broadcasts while another point just can listen without sending message, such as television and radio.
Half duplex
One point sends message and in this moment another point cannot send message and should wait until the first point finishes its transmission and then send its message, it is just a one communication line at a time, such as old wireless device walkie-talkie and HTTP protocol.
Full duplex
Both points can send and receive message at a time simultaneously, there is no need to wait until other point finishes its transmission such as telephones and websocket protocol.
Full Duplex
2. Server Sent Events (SSE)
The next choice for signalr is server sent event, because of persistence communication between server and client. In this approach, communication does not disconnect and last data from server will update automatically and transmit to client via HTTP connection. EventSource is part of HTML5 technology.
Hide Copy Code
<font color="#000000">var</font> evsrc = <font color="#000000">new</font> EventSource(<font color="#000000">"</font><font color="#000000">url"</font>);
<font color="#000000">
</font>
evsrc.addEventListener(<font color="#000000">"</font><font color="#000000">message"</font>, function (<font color="#000000">event</font>) {
<font color="#000000">
</font> });
3. Forever Frame
When client sends request to server, then server sends a hidden iframe as chunked block to client so this iframe is responsible to keep connection between client and server forever. Whenever server changes data, then send data as script tag to client (hidden iframe) and these scripts will be received sequentially.
4. Polling
Client sends request to server and server responses immediately but after that, server disconnects connection so again for establishing communication between server and client, we should wait for next request from client. To solve this problem, we have to set timeout manually and for each 10 seconds client sends request to server to check new modification in server side and gets last update data. Polling uses resources and it is not an economic solution.
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 request to server while in polling client has to send explicit request to server during timeout. Comet programming covers this concept. [4]
6. Socket.io
Socket.io is event driven and real time communication which has been abstracted all off five above technologies including websocket, forever frame and long pooling, in single API and allows application to send and receive data without worry. [5]
How to code Nodejs by the aid of Microsoft .Net
- Install Visual Studio 2015 , update 3 From Here
-
Install NodeJS From https://nodejs.org/en/
-
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 browser
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 remain them unchaged and press "Next"
Install NodeJS Tools for Visual Studio [6]
- 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 -> Visua Studio -> Create Project -> Templates -> JavaScript -> Node.js
- You also will have "npm" Nodejs Package Manager, which you will be able to install necessary libraries by it.
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('
' + data.message);
});
$(document).ready(function () {
$('#send').click(function () {
var msg = $('#text').val();
socket.emit('client_data', { 'letter': msg });
})
});
</script>
This is our conversation
<input id="text" type="text" /><button id="send">send</button>
How to use and run nodejs with .net
- Press F5 as it runs all of web application 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
- http://danielnill.com/nodejs-tutorial-with-socketio/
- https://en.wikipedia.org/wiki/Node.js
- https://nodejs.org/api/http.html#http_agent_sockets
- http://www.codeproject.com/Articles/732190/Real-Time-Web-Solution-for-Chat-by-MVC-SignalR-H
- https://nodesource.com/blog/understanding-socketio/
- http://www.codeproject.com/Tips/895385/Pictorial-Step-by-step-discussion-of-Nodejs-tools
- Socket.io
History
- First Version 4th July 2016
- Second Version 5th July 2016 : I have added graph to help better and easier understannding Nodejs code
Feedback
You are most welcome to vote and say your opinion to enhance quality of my article. So please do not hesitate to leave comment.