Saturday, December 14, 2013

WebRTC Introduction with chart flow

WbRtc stands for web real time communication which means you can share the audio and video stream, aribitrary data peer to peer. The WebRTC api is open source project introduced by GOOGLE.

In a web without any plugin, audio and video chat was very complex but WebRtc makes it simpler.
Now you don't need to any kind of plugin or extra technology. WebRtc with javascript makes you comfortable for sharing video, audio and other data.

So here we know, how it works.
You need the following points for use WebRTC in your web application
1) getUserMedia()
2) RTCPeerConnection object
3) Data Sharing

By the getUserMedia() method we can get the audio and video stream in codec format through the microphone and webcam respectively.

By using RTCPeerConnection object and signaling method, there could be share the network information like IP addresses, information about height, width and  resolution of local video(as this information is created by getUserMedia), The signaling method can be any which, like socket.io with node.js, ajax, xmpp etc. It's on you  which one is suitable for you.

Data Channel
After shared the above information there would be started audio and video streaming between peers.

So here we go in Detail,
We are supposing the user Sam is caller at one browser in one place, he gets the codec information about local video and audio.

The Rocky(callee) at other browser in other place, he also gets the codec information about local video and audio.

After that, browsers of Sam and Rocky are create the RTCPeerConnection Object(RTCPC) respectively in each browser.

As we already knew, Sam got the local information(codec information) about audio and video,  now he sets this information as local description to RTCPeerConnection Object(RTCPC), now he sends 'Creates Offer' with this local description to Rocky.

After get the local decription from Sam, Rocky sets that information as remote description to RTCPC object on his side, at the same time he sets his local description about video and audio to RTCPC object on his side and send it to Sam with 'Creating Answer'.

After get the 'creating answer' from Rocky , Sam sets that information/description as remote description to RTCPC object on his side.

The handler of onIceCandidate event is triggered when the candidate is available at network, which means When Rocky would availble at network, handler of onIceCandidate of Sam is triggered and sends the information about candidate  to Rocky, after that addIceCandidate of Rocky's side would be triggered.

After exchange these information, there would start audio and video streaming between peers Sam and Rocky.


Here is the process in chart which is devided into number.

chart webrtc



This article is inspired from below tutorial you can get more information about WebRTC from here.http://www.html5rocks.com/en/tutorials/webrtc/basics/

Tuesday, July 23, 2013

Closure in JavaScript

What is Closure

To understand the closure in JavaScript seems to be difficult, but not really. Let’s understand the concept step by step.

The Closure is a function which has access to variables of its outer function, that’s it, Is not this awesome? Let’s dive into the example

	var color = "red";
	function display(){
		var color2 = "green";
		console.log('Color are ' + color +  ' and ' + color2);
	}
	display();
With above code,  variable color can be overridden unintentionally at any time which may affect the action of display function.

So how above code can be protected by using closure concept.

var getColor = function (){
	var color  = "red"; // this can be accessed by display function
	var display = function(){ // this is closure function
		var color2 = "green";
		console.log('Color are ' + color +  ' and ' + color2);
	}
	return display;
}
var colorObj = new getColor();
colorObj('yellow');

In the above example, the ‘display’ is closure function, it can access the “color” variable whenever this function will be invoked, but this variable can not be accessed from outside of getColor function, so it’s safe for being override.

What’s is the benefit of using Closure?

By using the Closure, we can make our code private, clean, and variables can not be modified by unintentionally.

Seperate enviroment with Closure

In below example, every time the getColor is invoked there will create the exclusive environment with closure and it’s related variables.  For example

var getColor = function (color){
	var color  = color; 
	var display = function(){ 
		var color2 = "green";
		console.log('Color are ' + color +  ' and ' + color2);
	}
	return display;
}

var colorObj1 = new getColor('red');
var colorObj2 = new getColor('blue');

colorObj1('yellow');
colorObj2('geeen'); 

new getColor('red'); and  new getColor('blue'); create the specific environment.  The environment has its own variable values red and blue with its own closure. Below figure shows the enviroment for above code



After invoking the closure function display,  it uses the value which was passed during the getColor() function called.

What happens when closure is used under the loop

function display(color){
	console.log('color is ' + color);
}
var getColor = function (){
	var onColors = [];
	var colors  = ['red', 'green', 'blue']; 
	for(var i=0; i < colors.length; i++){
		onColors[i] = function(){
			display(colors[i]);
		};
	}
	return  onColors;
}
var onColors = getColor();
onColors[0]();

In the above code, when we invoke the function onColors[0](); It suppose to display red color but It does not happen, because when the display() closure is invoked, the i has been reached to 3, so the output is “color is undefined”.

Under the loop, the getColor is not able to create the individual environment because of which the i’s value 3 is shared to all closures onColors[i].

So we need to make the individual environment for each closure and it’ related variables under the loop. Let's see how do we achieve this.

	function display(color){
		console.log('color is ' + color);
	}
	
	function eachColorEnvironment(color){
		return function (){
			display(color);
		}
	}
	
	var getColor = function (){
		var onColors = [];
		var colors  = ['red', 'green', 'blue']; 
		for(var i=0; i < colors.length; i++){
			onColors[i] = eachColorEnvironment(colors[i]);
		}
		return  onColors;
	}
	
	var onColors = new getColor();
	onColors[0]();

In this example, onColors[0](); renders the output “color is red”. Now getColor() is able to create separate environment with specific value and closure from eachColorEnvironment, as following,

First environment => Red and Closure


Second environment => Green and Closure


Third environment => Blue and Closure

Use “let” instead of  Closure.
	function display(color){
		console.log('color is ' + color);
	}
	
	var getColor = function (){
		var onColors = [];
		var colors  = ['red', 'green', 'blue']; 
		for(var i=0; i < colors.length; i++){
			let color = colors[i];
			onColors[i] = function (){
				display(color);
			}
		}
		return  onColors;
	}
	
	var onColors = new getColor();
	onColors[0]();
	
We can use the let keyword to handle this situation, this keyword can be used for block scope variable, so let color = “colors[i]” defines the private variable for its own closures.
let color = colors[i];
onColors[i] = function (){ display(color);}	

You can get the various examples about Closure.

Tuesday, September 25, 2012

Callback Function

Callback function is very important into javascript. As we know we can pass different type of variable, object as function's parameter . In javascript if a function is passed as parameter then it is called Callback funbction.

The callback function is called on some event/condition till then the program can execute other code. We can say its uses the concept of asyncrhonous function. The callback function would executed only when the particular event is occurred or particular condition is satisfied.

Note:- Please don't forget to create a folder named image and place the image named(you can do rename) sham1.jpg inside that created folder. And of-course the below code and that folder should be exist into same directory.

Here is the exmaple, if there is any problem to understand code please share it with me.

<html>

<head>
<title>Call Back function</title>

<script type="text/javascript">
window.onload = function (){
loadImages(
//this functio runs only when the image would be 
// loaded into window
function (images, total){
  for(var i=0; i<total; i++){
 alert(images.src);
  }
}
);


function loadImages(callback){
var imgload = function (){
callback(myimage, 1);
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');

var myimage  = document.createElement('img');
myimage.onload = function (){
ctx.drawImage(myimage, 0, 10, 100, 100);
imgload();
}
myimage.src = "images/sham1.jpg";
}
}
</script>

</head>

<body>
<canvas id="myCanvas">
The canvas is missing in your browser
</canvas>
</body>

</html>

Monday, September 3, 2012

Prototype Introduction

Every object is an object of object. If we want to make the complex web application then we need to use prototype concept with Object Oritented at javascript in one level.

Object.prototype is an object whose properties and methods are inherited to new object when the new object is creating by using that constructor. The consctructor name would be same as for use to create new object.

Here we go for example.
var mydate = new Date();

Here via the Date.prototype, all the methods and properties of Date constructor would inherited to mydate object like getMonths() and getSeconds(). If you want to get month then you can simply do.
mydate.getMonths().
The getMonths() method is not user defined it is inherited from Date.prototype.

How do you use the prototype concept in your custom object. 
var mercidies = new Car();
function Car(name){
this.name = name;
}

Now if you want to add custom method to Car class then you can do.

Car.prototype.getValue = function (val){
var total = val + 100*(12.3/100);
}

For properites
Car.prototype.color = 'gray';

Now Every object is made by using Car() cunstroctur inherited getValue() method and color property.

So we can say prototype concept shares the information(properties and methods) to all those object which are created by using Car() cunstroctur.

So what is the main benfit of it?
It's main advantage is when we create the method and property by using object's prototype concept, methods and properties are shared to each instance made by using that paritcular cunstructor. Which means there is no need to make a copy of methods and properites for each instance.

And the result would be it uses less memory and the speed would be increase obviously.

What if the prototype concept is not exist?
For example simple class
function Car(){
this.name = name;
this.color = 'gray';
this.getValue  = function (){
var total = val + 100*(12.3/100);
}
}

When you make the instances by using that Car cunstructor then each instance/object copy those all properties and methods. Which is not good into complex web application.
If we use the concept of prototype then cunsctructor shares proprites and methods to each object. That's how its increase the speed.

Prototype Chains
By default every simple object has inherited the properties and methods from Object.prototype.
When the method and properties are accessing of objects, it travels through child to parent object.
For example

function Car(name){
this.name = name;
}

var myCar = new Car();
myCar.toString();

When the toString () is called first of all it sees that is it available in Car's prototype if yes then it returns particular value otherwise it heads to check for Object.prototype methods and returns the particular value if found the method otherwise returns null.



Sunday, June 10, 2012

Ajax long polling

At some application the client needs to check frequently that does some data is avialble on server? if yes then server does reponse it to client, for this the client need to do request frequently, which is not good because of performance point of view. So at this case we are using long polling method,

At this method once a client do a request to server for some response and whenever the response is available at server, it forwards to client. So through the Ajax long polling we set the particular timeout, and in that time a connection is being on between the server and client. Server will response the request whenever it gets the data. Overall process is called Ajax long polling.

Socket.io

socket.io is the module for node.js, it is made by using the concept of websocket. In simple words socket.io is the way to talk from client to server and from server to client. Well there is a very popular technology in the market is called websocket which does the same work  but not supported by all browsers, by default the websocket is available into html5.

Socket.io runs in all browser, so what it will do for run application in all browsers. Socket.io first makes the connection by using the websocket. If it's not supported by any browser then it uses another method for make connection. Here is the fallback transports by using socket.io
websocket,
htmlfile,
xhr-polling,(ajax long polling)
jsonp-polling
flash socket

socket.io makes the percistence connection between server and client. It shares the javascript code between server and client.  when the client emit the particular messesage along with keyword on particular event, At the same time in server the function would run which is associated with the same keyword that the browser emitted. Here is the example

CLIENT
socket.emit('doSomeWork', function (){
    ///some work here///
});

SERVER
socket.on('doSomeWork, function (){
        ///some work here///
});

"doSomeWork" is the same keyword which is shared betweent the client and server.

Saturday, June 9, 2012

Node.js's popularity

Why the node.js is so popular.

Node.js is made by using JavasScript language. Now you can write the javascript code into web server through the node.js, now we can share the javascript code between clent and server. Which can not be acheived by other server side language like php, ruby,  python.
As much as we can share the javascript code between client and server, the cost of web application would be less.

Javascript is event driving programming language, which means the block of code would be executed on particular event. The Node.js uses this concept for acheive high scalable server, You can say the work would be done with non-block concept through node.js, which means there the work could be done in parallel way, The  particular program does not wait to finish other particular work for start his/her work.

Node.js uses the chorme's  V8 JavaScript Engine (it compiles and executes the javascript) for increases the performance for particular application which is made by using node.js. On server some time there need to binary data manupulation so Node.js uses v8 javascript engine for it.

Friday, May 18, 2012

Hoisting Concept

Well I had the knowledge about variable scope in javascript but did not have the knowledge about hoisting, Two kind of variable scope we can get inside the javascript, first is global and other is local scope. 
The scope of variable is existing inside and outside of the function is called local and global scope respectively. 

In language C and the kind of language, a variable scope is rely under the opening and closing curly braces. In javascript the variable scope is live on under the function. for example 
function example(){
   var i = 100;
   if(i==number){
       if(i == 100){
           var j= 900;
       }
   }else(){
       var k=80;    
   }
} 
Inside the example() function all the variable i, j and k have same variable scope.  Which means a variable we can get inside the function before that variable is declared, the process is known as 'hoisting', which means the variable do behave like they all are declared at very start of function. 

Lets understand it with example. Before that we should know one thing, If we declared the variable without 'var' keyword then its behave like a global variable of particular object under it's chain. 
 Here is the example of hoisting 
var mycar = 'bmw'
function example(){
   alert(mycar);
   var mycar = 'toyata';
   alert(mycar);
} 

It seems that first alert would be the value with 'bmw' but its not like this but it would be alert with value 'undefined' because of hoisting concept(because it's behave like the variable is declared at very start of function). The first 'mycar' would be  hidden because with the same name another variable is declaring inside the function. 

At first alert of 'mycar', the value 'totyata' is not alerting because the line(var mycar = 'toyata';) of function is not executed yet. The 'toyata' would be displayed into second alert. 

It is good practice to declare the variable near where the variable would be used.

Saturday, May 12, 2012

Wrapper Object

In JavaScript everything is about method and property.  There is different type of object. Wrapper object is also one of them. Every object has property and method. So what is the different concept in wrapper object, There we can get the different property and method for string, for example
var myVal = “hello”;
myVal.length;
myVal.indexof(‘h’);
Here myVal is not object however we are using property(length) and method(indexof) to reach that object for particular task. It happens all because of wrapper object concept; 
In simple words when we call the property and method for particular string, at the same time there will be created a temporary object (which is called wrapper object also). When myVal.length is invoked then the temporary object would be made
.
Lets see what happens after created the temporary object with example,
var mystring = “sumanbogati
var newval = mystring.length;
alert(newval)

After executed the line var newval = mystring.length;” the temporary object(wrapper object) would be deleted. One more thing is interesting that we can not assign the value to property of string, for example

var mystring = “sumanbogati”
mystring.length = 5
var newval = mystring.length;

The new value would not be 5 but 10 original one.
The same concept would be apply to number and boolean also.


Sunday, April 29, 2012

Variable with and without 'var' keyword into JavaScript

When we  declaring the JavaScript variable actually we are creating the property of JavaScript global object. We can define the variable into JavaScript with  and without 'var' keyword, What is the main difference on it?.
When we used the 'var' keyword for define the variable then it is not configurable which means it can not be deleted by delete operator whereas in case of not using the 'var' into variable then the variable would be configurable which means it can be deleted by delete operator.

Please take care of it and always try to define a variable with 'var' keyword.

Friday, February 24, 2012

First Article for javascript

Well it's been more than 3 year I have known about JavaScript, I have learned almost One and half year JavaScript and Jquery. I have the knowledge about YUI scrpits little bit. But I did not get much chance to explore my javascript knowledge, Now I want to be real expert into JavaScript. So from today I have to started to work on it...

Lets Enjoy the JavaScript, :)