Thursday, 29 September 2016

Network Communication Protocols( UDP and TCP)

The UDP and TCP protocols are two different protocols that handle data communications between terminals(servers) in an IP network.
Both are Transport Layer Protocols.

UDP is - connection less protocol.(unreliable)
TCP is - connection oriental protocol.(reliable)

TCP needs connection between source and destination before transfer of data.

1.Because TCP is a connection-oriented protocol responsible for ensuring the transfer of a data from the source to destination machine.
2.TCP must receive communications messages from the destination machine to acknowledge receipt of the data.
3. IP simply handles the routing of data; and if problems occur, IP discards the packet without a second thought, generating an error message back to the sender in the process.
If data is corrupt or lost, It is the TCP which handles retransmission.


Unlike TCP, UDP doesn't establish a connection before sending data, it just sends. Because of this, UDP is called "Connectionless".

Why UDP is faster than TCP ?
No error checking,error correction, or acknowledgment is done by UDP.
UDP is only concerned with speed.
 

Selection Criteria  for UDP or TCP-
UDP is never used to send important data such as web-pages, database information, etc.
Streaming media such as video,audio and others use UDP because it offers speed.

Differences -
Tcp&udp.jpg

Tuesday, 27 September 2016

JavaScript Basics

JavaScript is a dynamic programming language that, when applied to HTML document ,can provide interactivity on website.
What is dynamic behavior?
We do not need to define type of variable. It is automatically determined when a program is executed. 

Applications -
1.Creation of  games
2.Fully Blown database driven applications (MEAN development)
3.Animation using 2D,3D graphics.

JavaScript can be used for Front End Development (Rich Interactive UI) as well as Server End Development (with NodeJs).

Hence Full Stack Development of SPA(Single Page Application) is possible with JavaScript.
1.GMAIL (is SPA)
2.MEAN Development (MongoDB,Express,AngularJS,NodeJs)
.
Precisely except simple data types such as String, Number, Boolean, Null and Undefined
every other defined thing  in JavaScript is an Object such as Array, Functions etc. and such objects can be stored in variable
Comments-
1.Multiple lines - /*.........*/
2.single line - //This is comment.

Variables -
1. var name= "daniel";              //local or global variable depending on where it is declared.
2. name="daniel";                     //global variable declaration.
3. window.name="daniel";      //global variable declaration. (as same as 2)
4. const constant =100;            //constant variable declaration

Data Types -
A.Primitives 
1.String           var str = "tushar";
2.Number        var num = 100;
3.Boolean        var isBoolean = true ;
4.Null              var noValue = null;
5.Undefined    //When variable has no assigned value.
 B.Object
1.Object          All above examples.          //Every variable in JavaScript is Object.
2.Array            var arr = [''Tushar",12,"Anil",20];
3.Functions     function callMe(){return "hello"};

How to create Object in JavaScript?
1.var obj = {a:22};                                   //JavaScript Object Literal == JSON Object.
2.var arr = [11,"testMe",22];
3.var today = new Date();


Operators -
1.Add/Concatenation     var sum =2+3;  and  var joinStr = "Hello"+"Tushar";
2.Identity Operator(Strict)     ===         //Checks only whether two values are equal.
                                              ! or !==    //negation 
3.Identity Operator (Loose)   ==          //Converts data types when data types are not equal then checks
                                                           // values.
                                              !=           //negation
Hence always wise to use Strict operator to avoid data type conversion issues.

Conditional Operator (Ternary)- 
Used to assign value to variable based on conditions.
This is replacement for If-Else Loop.
Syntax- condition ? exp1(if true):exp2(if false)
Eg.
var ageGroup = age ? 1:0;   

//if age is true --> ageGroup = 1;
//else ageGroup =0;

Functions- 
How to define anonymous function?
var callMe = function(a){console.log(a*a); };   //function assigned for a variable.
calling function -->
callMe(5);

Output will be- 25.
 //This is as same as defining a function and calling it whenever needed. 

How to create Objects in JavaScript ?
JavaScript is Object based language.
Means, we do not create Class to create objects but we directly create Objects.

3 ways to create objects -
1.Object Literal
var emp = { id:007, name:"Tushar",salary:40000}   //Similar to Json Object

2.By creating instance of Object 
var test = new Object();

test.id =007;
test.name ="tushar";
test.salary =40000;

3.By using Object Constructor. 
function emp(id,name,salary){
this.id =id;
this.name=name;
this.salary=salary;
}


var test = new emp(007,"Tushar",40000);

JavaScript In-Built Objects - 
1.Object
2.String
3.Math
4.Function 
5.Array
6.Date etc. Hence JavaScript is called as Object Based language.

Browser Object - 
Window
Window is browser object and not JavaScript Object. 

JavaScript String Concatenation -
Note** - After First String occurrence all next + operator are treated as concatenation operators.
Eg.
var sum = 10+10+"30"  //sum is 2030
var sum ="10"+10+10   //sum is 101010

Difference between Client side JavaScript and server side JavaScript ? 
Client side javaScript is directly interpreted in Browser JavaScript Engine at runtime.
Server side javaScript is always complied before executing. 

 

 







 



 

Thursday, 22 September 2016

Difference Between ByteCode and Machine Code?

Machine Code is set of instructions that is directly understood by the CPU processor (Hardware).
Hence it is platform independent.

Whereas, Byte Code is set of instructions directly understood by Virtual Machine( JVM ).
Hence it is platform dependent

What is V8 JavaScript Engine?

It is JavaScript Engine developed for web browser Google Chrome .
             JavaScript Engine is Program or Library that helps to compile and execute JavaScript code.
It mainly used in Web Browsers.

Examples of JavaScript Engines-
V8- Chrome
Rhino -Firefox
Chakra - Microsoft IE 

V8 complies JavaScript code to machine code before executing it.

Traditional Approach is compiling whole program to machine code before executing it.
Instead V8, optimizes complied code at runtime.


Applications -
NodeJs, MongoDB, and Couchbase use V8 engine

Uses ->
Client Side Applications - Chrome (All Browsers)
Server Side Applications - NodeJs

**Advantages -
1.It is much faster than its peers because it compiles code directy to machine code without generating byte code(intermediate code).
2.It uses 2 compilers to compile code one after another.Second run compiler mainly optimizes main functions.

What is ECMAScript (ES) and how it is related to JavaScript (JS) ?

ECMA stands for European Computer Manufacturer's Association.
ECMAScript or ES is a standard for a scripting language given by ECMA.
It specifies the core features that a scripting language should provide and how those features should be implemented.

ES has various versions-
ES4- Abandoned
ES5- launched in 2011
ES6- launched in 2015
ES7- Finalized in 2016.

Whereas,
JavaScipt or JS is the most popular implementations of the ECMAScript Standard.

Note**- Every browser has a JavaScript interpreter.

Imp Implementations of ES ->
1. JavaScript V8 Engine.  - Engine used by Google Chrome to compile and interpret ES.
2. Jscript - used by Microsoft Internet Explorer (compiles and interprets ES )
3. JavaScript

Tuesday, 13 September 2016

Using Sockets

Sockets are used to communicate 2 different processes  on same or different machines.

Application ->
For Eg.
Suppose a JavaScript Application want to send Message to Java Application(JAR file.)
Hence we can communicate JavaScript and Java Application using sockets.

Also, If processes are running on different machines then socket is used as a common ground to communicate both processes.

How to use ->
Socket has 2 parts ->
1.Client -> App which sents/request data to another app
2.Server -> App which processes/responds to sent request.

In Order to make Socket Object we need IP and Port.

Here I am using an example in which client sends 2 no a and b to server. Server then adds them and returns the result.

I am using nodeJs and Javascript  

Client Part (Client.js)
Client selects IP and PORT to establish Socket.
    
var JsonSocket = require('json-socket');//Client Details
var HOST = "172.16.207.151";
var PORT = "6969";
//same port where server is listening...
// Make a sokcet with JSONSocket
var socket = new JsonSocket(new net.Socket());
//Create instance of server and wait for connection
socket.connect(PORT, HOST);
console.log('Server listening on ' + HOST + ':' + PORT);

socket.on('connect', function () {
//Don't send until we're connected
//On connection sending no a and b to server to multiply.
    socket.sendMessage({ a: 5, b: 7 });
   
//on getting result from server print it.
    socket.on('message', function(message) {
        console.log('The result is: '+message.result);
    });
});








Server Part (Server.js)
Sever only needs to listen to port where client is sending data

var net = require('net');
JsonSocket = require('json-socket');
var PORT = "6969";
var server = net.createServer();
server.listen(PORT);
server.on('connection', function(socket) {
//This is a standard net.Socket
    socket = new JsonSocket(socket);
//Now we've decorated the net.Socket to be a JsonSocket
    socket.on('message', function (message) {
        console.log("Message Received on server");
        var result = message.a + message.b;
        socket.sendEndMessage({result: result});
    });
});
How to test?
First run server.js and then client.js
output: 
on Client Side->
Server listening on 172.16.207.151:6969
The result is: 12

on Server side->
Message Received on server
 

I Hope this helps.


Difference between noClassDefFoundError and ClassNotFoundException

Before discussing the difference lets talk about their similarities.
1.Both occur because of  the unavailability of class at runtime at classpath.

Differences -
1.noClassDefnFoundError is error and cant be handled while ClassNotFoundExceptionis exception and can be handled.

2.The exception occurs when we try to load class at runtime using
Class.forName()  or
ClassLoader.loadClass()

In short,
The difference is the root cause of the problem->

ClassNotFoundExcpetion occurs when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath  
Eg.
Your are trying to load jar file and that jar file is not found in classPath.

 noClassDefFoundError occurs when requested class was present at compile time but not available at runtime.
 This happens because of exception during class Initialization.

How to test?
Step1- Create below files -
1. Test.java -->
 public class Test {}
2.Test1,java-->
public class Test1{
Test test = new Test();
}

Step 2.Now compile Test1.java
javac Test1.java
 2 class files will be generated Test.class and Test1.class

Step3. Now delete Test.class file and run Test1.java

noClassDefnFoundError occurs.
 

Monday, 12 September 2016

Javac is not recognised as internal or external command...

Whenever we try to compile .java file to .class file we often get this message.
It means that java compiler (javac.exe) is not found by OS in the current path.

So we need to tell OS where we have stored javac.exe.

Hence, Execute below command
set PATH ="C:\Program Files (x86)\Java\jdk1.8.0_31\bin"
where bin folder contains javac.exe

Now OS knows where javac is present and it will compile the java files successfully.

Difference between program files and program files(*86) on windows OS?

A 64 bit windows OS has 2 different but similar folders
1.Program Files - which contains 64 bit applications
2.Program Files(*86)- which contains 32 bit applications.


This is because, windows run both 32 bit and 64 bit architectural programs on 64 bit OS.
I do not know why it does not use all 64 bit programs on 64 bit OS ?


In short, 32 bit architectural programs are stored under Program Files(*86) and
64 bit architectural programs are stored under Program Files.

How to create jar file from Java Project and Run using Command Prompt?

I am using eclipse.

Create Java Project and add few classes to it.
Now a jar file can be exported as JAR or Runnable JAR.

The Difference between JAR and Runnable JAR is that the later has Entry point( Main Class) defined in it so that if we run the jar from command Prompt  it gets executed.

Steps ->
1.Right click on project and select Export 
2.Select Runnable JAR option and Click Next
3.Now select Entry Point in Launch Application Option. (Eg. Main Method)
4.Save .

Now your JAR file is created.
Each JAR file has  META-INF/MANIFEST.MF file which has default settings.
But when we create jar File as Runnable JAR entry point gets created in MANIFEST.MF file
as Main-Class:PackageName.ClassName  
Eg. Main-Class:com.tush.pat.TestClass

Whenever entry point is not mentioned in class add above line to it and then run .

Note**-
Whenever we create jar file simply as JAR we often miss to mention entry point in jar .
Hence jar file first has to be made runnable and then run.

To avoid it we can directly create runnable jar.

How to run ?
1.Open cmd and cd to jar file location.
2. java -jar abc.jar    
 where abc.jar is our jar file

It will execute the jar file.