Monday, 9 February 2015

Web Socket

  Web Socket:
                     To use a single TCP connection for  traffic in both directions.  This is what the WebSocket Protocol  provides.  Combined with the WebSocket API [WSAPI], it provides an alternative to HTTP polling for two-way communication from a web page to a remote server.

  The same technique can be used for a variety of web applications:games, stock 
tiers, multiuser applications with simultaneous  editing, user interfaces exposing server-side services in real time,etc.


Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.
Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessageevent handler.
A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data.
Following is the API which creates a new WebSocket object.
var socket= new WebSocket(url, protocol[optional]);
Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.

WebSocket Attributes:

AttributeDescription
Socket.readyState
The readonly attribute readyState represents the state of the connection. It can have the following values:
  1. A value of 0 indicates that the connection has not yet been established.
  2. A value of 1 indicates that the connection is established and communication is possible.
  3. A value of 2 indicates that the connection is going through the closing handshake.
  4. A value of 3 indicates that the connection has been closed or could not be opened.
Socket.bufferedAmount
The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method.

WebSocket Events:

Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above:
EventEvent HandlerDescription
openSocket.onopenThis event occurs when socket connection is established.
messageSocket.onmessageThis event occurs when client receives data from server.
errorSocket.onerrorThis event occurs when there is any error in communication.
closeSocket.oncloseThis event occurs when connection is closed.

WebSocket Methods:

Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above:
MethodDescription
Socket.send()
The send(data) method transmits data using the connection.
Socket.close()
The close() method would be used to terminate any existing connection.

WebSocket Example:

A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data.

Client Side HTML & JavaScript Code:

At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://localhost:9998/echo");
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>

Saturday, 31 January 2015

File backup(tar/gzip)

 Linux is an "almost perfect" operating system, but things do happen and data is sometimes lost. The best way to avoid problems is to backup your files. Linux provides two key programs to do this: 'tar' and 'gzip'

Tar:
This program assembles various files into one package, commonly called a "tarball". Let's say you have some files - notes say:
notes1.txt
notes2.txt
notes3.txt

we placed these files under a directory named linux_notes and We  want to back them up and keep them on a floppy, let's say. You would type the following command to package them in a tarball.

tar -cvf linux_notes.tar notes*.txt

First, We have tar, the name of the program. Then we have the options, c (--create) v (--verbose-show what files they are) (f--file -make a file - should always be the last option) Then we have the name of the file we want to create ( linux_notes.tar) and the files we  want to backup (notes*.txt).

This presupposes that you may have other files in the directory that you don't want to include. If you want to include ALL files in a directory, just substitute notes*.txt for *.*.

tar -cvf linux_notes.tar *

With one asterisk, you will include directories and files without extensions (my_file as opposed to my_file.txt). Be prepared to get a fairly voluminous tarball.

This is the first step in the backup process. Now let's look at the second step; the compression of these files.


Using 'gzip'

As we mentioned, 'tar' just assembles the files together into only one file. There is no reduction in the size of these files (the tarball might even be bigger!) Now we would have to do one more thing in order to reduce this file into a more manageable size: use 'gzip'.

gzip is the preferred compression tool for Linux. To reduce the size of your tar file, you would issue the following command:

gzip linux_notes.tar
and the tar file would be compressed. You can also compress a regular file using the same command, but gzip is used primarily with tarballs.

The result would be a file like this: your_tar_file.tar.gz

The two file extensions show us that the file is a tarball and it is compressed with the 'gzip' format.

We can reduce these two steps into one means we can  create the .tar.gz file at the same time when we make the tarball.
If you add z to the options, and change the name of the file to create to a .gz extension, you have the whole shebang in one step.

tar  -czvf linux_notes.tat.gz  notes.*txt

Remember f should always be the last option.

Untar:

tar -zxvpf  linux_notes.tar.gz

I've used my preferred options. I'll explain them:

-z - unzip the file first
-x - extract the files from the tarball
-v - \&quot;verbose\&quot; (i.e tar tells you what files it's extracting)
-p - preserves dates, permissions of the original files
-f - use the file in question (if you don't specify this, tar just sort of sits around doing nothing)

The files are extracted and your original tarball is preserved (my_tar_file.tar.gz).

We can ommit the option z
tar -xvpf linux_notes.tar.gz


To unzip the .gz file
gzip -d linux_notes.tar.gz

This will result a tarball  named linux_notes.tar

Now  we can extract the files from the tarball
tar -xvpf linux_notes.tar


Folder Zip:

Sometimes we need to zip the  files of directory and subdirectory within the directory and files & subdirectory of subdirectory and so on. So to Zip use:

zip -r filename.zip  directory_to_zip_recursively

and to unzip

unzip filename.zip








History of Browsers

The first web browser was invented in 1990 by Sir Tim Berners-Lee.
The first commonly available web browser with a graphical user interface was Erwise. The development of Erwise was initiated by Robert Cailliau.

In 1993, browser software was further innovated by Marc Andreessen with the release of Mosaic, "the world's first popular browser.
Microsoft responded with its Internet Explorer in 1995.
Opera debuted in 1996; it has never achieved widespread use.
In 1998, Netscape launched what was to become the Mozilla Foundation in an attempt to produce a competitive browser using the open source software model. That browser would eventually evolve into Firefox, which developed a respectable following while still in the beta stage of development.
Apple's Safari had its first beta release in January 2003; as of April 2011.
The most recent major entrant to the browser market is Chrome, first released in September 2008.

This process begins when the user inputs a Uniform Resource Locator (URL), for example http://en.wikipedia.org/, into the browser. The prefix of the URL, the Uniform Resource Identifier or URI, determines how the URL will be interpreted. The most commonly used kind of URI starts with http: and identifies a resource to be retrieved over the Hypertext Transfer Protocol (HTTP). Many browsers also support a variety of other prefixes, such as https: for HTTPSftp: for the File Transfer Protocol, and file: for local files. Prefixes that the web browser cannot directly handle are often handed off to another application entirely. For example, mailto: URIs are usually passed to the user's default e-mail application, and news: URIs are passed to the user's default newsgroup reader.


Port number

Definition - What does Port Number mean?

A port number is the logical address of each application or process that uses a network or the Internet to communicate. A port number uniquely identifies a network-based application on a computer. Each application/program is allocated a 16-bit integer port number. This number is assigned automatically by the OS, manually by the user or is set as a default for some popular applications.

A port number primarily aids in the transmission of data between a network and an application. Port numbers work in collaboration with networking protocols to achieve this. For example, in an incoming message/packet, the IP address is used to identify the destination computer/node, whereas the port number further specifies the destination application/program in that computer. Similarly, all outgoing network packets contain application port numbers in the packet header to enable the receiver to distinguish the specific application. 
Port numbers are mainly used in TCP and UDP based networks, with an available range of 65,535 for assigning port numbers. Although an application can change its port number, some commonly used Internet/network services are allocated with global port numbers such as Port Number 80 for HTTP, 23 for Telnet and 25 for SMTP.

Friday, 30 January 2015

Working with Remotes in Git

First of all must have all the dependencies in your system

1 .sign up at Remote like github.
2. generate ssh key  in your system ,

 SSH: 
 In your home directory that is /Users/Jitendra , there is a directory .ssh which contains two         files named: 
 id_rsa(private key) and 
 id_rsa.pub(public key)

and link this with your remote host e.g. github

3. Now create a blank repository  on github. and clone it in your working directory.

$ git clone git@github.com:Jitu1990/gittest.git

At this point  your remote is set with origin , to see it run:

$ git remote -v
origin: git@github.com:Jitu1990/gittest.git

Working with remotes

Showing your remotes

To see which remote servers you have configured, you can run git remote the command. It lists the shortnames of each remote handle you’ve specified. If you’ve cloned your repository, you should at least see —that is the default name Git gives to the server you cloned from: 

$ git remote
origin
$ git remote -v
origin git@github.com:Jitu1990/gittest.git

Adding New Remote
Note: you can add a new remote Git repository as a short- name you can reference easily, run git remote add [shortname] [url]

$ git remote add pb  https://github.com/Jitu1990/gittest.git

Now track your files and commit changes. If you want to push the changes back to remote host. you can do it with these command .

Inspecting a remote

$git remote show origin


This command shows which branch is automatically pushed when you run
on certain branches. It also shows you which remote branches on the server you don’t yet have, which remote branches you have that have been removed from the server, and multiple branches that are automatically merged when you run


Removing and Renaming a remote
$ git remote rename gitssh gitsshtr

$ git remote remove gitsshtr


Push your commit:
You can push either using https or ssh.
$ git push [remote-name] [branch -name]

eg. $git push origin master


This command works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime. If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected. You’ll have to pull down their work first and incorporate it into yours before you’ll be allowed to push.  

Note: if you push through https it will ask you remote(github) user name and password:
eg.
   $ git push pb master
Username for 'https://github.com': Username
Password for 'https://jsolanki272@gmail.com@github.com':

That means you can have multiple remote 
$ git remote -v
badkoor git://github.com/bakdoor/tickgit.git
cho45   git://github.com/cho45/grit.git
pb      https://github.com/Jitu1990/gittest.git
origin  git@github.com:Jitu1990/gittest.git

This means I can pull contributions from any of these users pretty easily. But notice that only the remote is an SSH URL, so it’s the only one I can push to  .

Pull Repository:
To pull a repository, run:
$git pull


How pull is different from fetch ?

To get data from your remote projects, you can run

$ git fetch [remote-name]

The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time. 

  $ git fetch origin 

fetches any new work that has been pushed to that server since you cloned (or last fetched from) it. It’s important to note that the command pulls the data to your local repository—it doesn’t automatically merge it with any of your work or modify what you’re currently working on. You have to merge it manually into your work when you’re ready. 


you have a branch set up to track a remote branch you can use the  git pull command to automatically fetch and then merge a remote branch into your current branch. This may be an easier or more comfortable workflow for you; and by default, the command automatically sets up your local master branch to track the remote master branch on the server you cloned from (assuming the remote has the master branch)


Running generally fetches data from the server you originally cloned from and automatically tries to merge it into the code you’re currently work- ing on. 






Webserver VS Application Server


  • Web server: serves content to the web using http protocol.
  • Application server: hosts and exposes business logic and processes.

    Following are some of the key differences in features of Web Server and Application Server:
    • Web Server is designed to serve HTTP Content. App Server can also serve HTTP Content but is not limited to just HTTP. It can be provided other protocol support such as RMI/RPC
    • Web Server is mostly designed to serve static content, though most Web Servers have plugins to support scripting languages like Perl, PHP, ASP, JSP etc. through which these servers can generate dynamic HTTP content. 
    • Most of the application servers have Web Server as integral part of them, that means App Server can do whatever Web Server is capable of. Additionally App Server have components and features to support Application level services such as Connection Pooling, Object Pooling, Transaction Support, Messaging services etc.
    • As web servers are well suited for static content and app servers for dynamic content, most of the production environments have web server acting as reverse proxy to app server. That means while servicing a page request, static contents (such as images/Static HTML) are served by web server that interprets the request. Using some kind of filtering technique (mostly extension of requested resource) web server identifies dynamic content request and transparently forwards to app server.
    • Example of such configuration is Apache Tomcat HTTP Server and Oracle (formerly BEA) WebLogic Server. Apache Tomcat HTTP Server is Web Server and Oracle WebLogic is Application Server.

Thursday, 29 January 2015

Git and GitHub

What is Git?
Well, Git is not Github. Git is a piece of software that you install locally on your computer which handles 'version control' for you.

What is Version Control?
Let's say you have some new project, and you are planning to store all the files for that project in some new directory. You know that as time goes on, the files in this project will change - a lot. Things could get messy, and who knows when you might need to revert back to a previous working version of what you had?
So, you install Git on your computer. Then, you have Git create the new project directory for you. You also tell Git that you would like to keep a history of the changes you make within that directory.
Then, you add some files to kick off your project. The files you just added represent the first incremental step on the journey of your project. So you tell Git to take a snapshot.
Then you make a small change - your next incremental step. So you take another snapshot.
And that's about it for version control - make a small change, take a snapshot, make another small change, take a snapshot. You can then use Git to step back and forth whenever necessary through each snapshot (snapshot aka version) of your project directory. Hence, version control.

Collaborating with Git
That's great for you as an individual. But what if you are working on a team, and you want to share your project directory? And you want to make changes on your machine, send those changes to your collaborators, and also have changes they make appear in your machine's project directory?
Git is a so called distributed version control system. All that means is that Git has commands that allow you to push and pull your changes to other people's machines:
Collaborating using Git

Neither copy of the project directory is any better or 'greater' than any other - you are both collaborating on identical copies. This is a good thing, and Git gives you the power to work on your own copy as-is until you are ready to pull in your collaborator's changes, and push back your own changes.

Wouldn't it be great if there were a third identical copy you could both push and pull from?

Collaborating with Git and GitHub
Well, that's what Github is! At it's core, it's just a place to store your identical working directories - aka repositories, or repo's for short. That's the service that Github provides - it's literally a hub for Git repositories.
Collaborating using Git and GitHub
Git allows you to snapshot/commit incrementally, after each little change you do. I regularly have 10 commits per day, and I or anyone can cycle back and forth through those snapshots any time we like.

Alternatives to Github
Since Git and Github aren't really linked - Github is just another place to store identical repos - you could use any Git hosting service. One alternative is Bitbucket. This service gives you free private repos (unlike Github), in case you aren't ready to share your work with the world.
However Github is the most widely used Git hosting service, and has a broad community of users sharing code and interacting.

Basic Unix commands

1.1 Listing files and directories

ls (list):

    The ls command ( lowercase L and lowercase S ) lists the contents of your current working directory.
Files beginning with a dot (.) are known as hidden files and usually contain important program configuration information.
To list all files in your home directory including those whose names begin with a dot, type 
  $ ls -a

1.2 Making Directories

mkdir (make directory):

make a subdirectory called unixstuff in your current working directory type
$ mkdir unixStuff

This will create a new subdirectory in your current working directory.
To see the directory you have just  created

$ ls

1.3 Changing to a different directory

cd (change directory):

The command cd directory means change the current working directory to 'directory'
To change to the directory you have just made, type

$ cd unixStuff

1.4 The directories . and ..

Still in the unixstuff directory, type
$ ls -a

in the unixstuff directory (and in all other directories), there are two special directories called (.) and (..)

The current directory (.)

In UNIX, (.) means the current directory, so typing
$ cd .

means stay where you are (the unixstuff directory).

The parent directory (..)

(..) means the parent of the current directory, so typing

$ cd ..
will take you one directory up the hierarchy (back to your home directory). Try it now.
Note: typing cd with no argument always returns you to your home directory. This is very useful if you are lost in the file system.

1.5 Pathnames

pwd (print working directory):

Pathnames enable you to work out where you are in relation to the whole file-system. For example, to find out the absolute pathname of your home-directory, type cd to get back to your home-directory and then type
$ pwd

The full pathname will look something like this -
/Users/Jitendra

1.6 More about home directories and pathnames

Understanding pathnames

First type cd to get back to your home-directory, then type
    $ ls unixstuff
to list the conents of your unixstuff directory.
Now type
$ls backups
You will get a message like this -

ls: backups: No such file or directory

The reason is, backups is not in your current working directory. To use a command on a file (or directory) not in the current working directory (the directory you are currently in), you must either cd to the correct directory, or specify its full pathname. To list the contents of your backups directory, you must type

$ ls unixstuff/backups

~ (your home directory):

Home directories can also be referred to by the tilde ~ character. It can be used to specify paths starting at your home directory. So typing

$ ls ~/unixstuff

will list the contents of your unixstuff directory, no matter where you currently are in the file system.

$ ls ~

will work same as ls. it will list the content of current working directory.

$ls ~/..

will list the content of the parent directory of the current working directory.



Summary


                             
CommandMeaning
lslist files and directories
ls -alist all files and directories
mkdirmake a directory
cd directorychange to named directory
cdchange to home-directory
cd ~change to home-directory
cd ..change to parent directory
pwddisplay the path of the current directory




2.1 Copying Files



cp (copy):

What we are going to do now, is to take a file stored in an open access area of the file system, and use the cp command to copy it to your unixstuff directory.

First, cd to your unixstuff directory.
$ cd unixstuff

syntax:
$ cp [path of the file] .(dot)
 $ cp ~/Desktop/Git_intro.txt .

Note: Don't forget the dot . at the end. Remember, in UNIX, the dot means the current directory.

The above command means copy the file Git_intro.txt from Desktop to the current directory, keeping the name the same.

2.2 Moving files

To move a file from one place to another, use the mv command. This has the effect of moving rather than copying the file, so you end up with only one file rather than two.
It can also be used to rename a file, by moving the file to the same directory, but giving it a different name.

cd to current working working directory then type

$ mv Git_intro.txt MyGit.txt

2.3 Removing files and directories

To delete (remove) a file, use the rm command.

$ rm Git_intro.txt

You can use the rmdir command to remove a directory (make sure it is empty first).
$ rmdir backups

2.4 Displaying the contents of a file on the screen

clear (clear screen):

$ clear

This will clear all text and leave you with the % prompt at the top of the window.

cat (concatenate):

The command cat can be used to display the contents of a file on the screen. Type:
$ cat Git_intro.txt

As you can see, the file is longer than than the size of the window, so it scrolls past making it unreadable

less:

The command less writes the contents of a file onto the screen a page at a time. Type
$ less Git_intro.txt

Press the [space-bar] if you want to see another page, and type [q] if you want to quit reading. As you can see, less is used in preference to cat for long files.

head:

The head command writes the first ten lines of a file to the screen.

$ head Git_intro.txt

$ head -5 Git_intro.txt
 This will writes the first 5 lines of a file.

tail:

The tail command writes the last ten lines of a file to the screen.
$ tail Git_intro.txt


2.5 Searching the contents of a file

Simple searching using less:

Using less, you can search though a text file for a keyword (pattern). For example, to search through science.txt for the word 'science', type

$ less Science
 This will show the first page of the file.

then, still in less, type a forward slash [/] followed by the word to search
/science

As you can see, less finds and highlights the keyword. Type [n] to search for the next occurrence of the word.

grep (don't ask why it is called grep):

 It searches files for specified words or patterns. 

$ grep science Science.txt

As you can see, grep has printed out each line containg the word science.

The grep command is case sensitive; it distinguishes between Science and science.

To ignore upper/lower case distinctions, use the -i option, i.e. type

$ grep -i science Science.txt

To search for a phrase or pattern, you must enclose it in single quotes (the apostrophe symbol). For example to search for spinning top, type

$ grep -i 'spinning top' Science.txt

Some of the other options of grep are: 
-v display those lines that do NOT match
-n precede each matching line with the line number
-c print only the total count of matched lines 


wc (word count):

To do a word count on science.txt, type
$ wc -w science.txt

To find out how many lines the file has, type:
$ wc -l science.txt

Summary


CommandMeaning
cp file1 file2copy file1 and call it file2
mv file1 file2move or rename file1 to file2
rm fileremove a file
rmdir directoryremove a directory
cat filedisplay a file
less filedisplay a file a page at a time
head filedisplay the first few lines of a file
tail filedisplay the last few lines of a file
grep 'keyword' filesearch a file for keywords
wc filecount number of lines/words/characters in file




3.1 File system security (access rights)

$ ls -l

you will see something like this
-rwxr-xr-x@ 1 Jitendra  staff  3905926 Jan 29 11:49 pro-git-chacon.pdf

Each file (and directory) has associated access rights, which may be found by typing ls -l. Also, ls -lg gives additional information as to which group owns the file.

You will get the details of your directory.
the left most string is of size 9.
the left most bit in string indicates that whether it's a file or directory.
If it is a directory it will show d otherwise - 
the first three(from left) shows the permission for the owner of the file.
Second three bits shows the permission for the group.
and last three bit shows permission for all others.


Access rights on files.

  • r (or -), indicates read permission (or otherwise), that is, the presence or absence of permission to read and copy the file 
  • w (or -), indicates write permission (or otherwise), that is, the permission (or otherwise) to change a file 
  • x (or -), indicates execution permission (or otherwise), that is, the permission to execute a file, where appropriate 

Access rights on directories.

  • r allows users to list files in the directory; 
  • w means that users may delete files from the directory or move files into it; 
  • x means the right to access files in the directory. This implies that you may read files in the directory provided you have read permission on the individual files. 
So, in order to read a file, you must have execute permission on the directory containing that file, and hence on any directory containing that directory as a subdirectory, and so on, up the tree. 

3.2 Changing access rights

chmod (changing a file mode)

Only the owner of a file can use chmod to change the permissions of a file. The options of chmod are as follows

              
SymbolMeaning
u
user
g
group
o
other
a
all
r
read
w
write (and delete)
x
execute (and access directory) 
+
add permission
-
take away permission

 to remove read write and execute permissions on the file biglist for the group and others, type

      $ chmod go-rwx bilglist

This will leave the other permissions unaffected. 
To give read and write permissions on the file biglist to all,

$ chmod a+rw biglist


3.3 process and jobs

A process is an executing program identified by a unique PID (process identifier). To see information about your processes, with their associated PID and status, type

$ ps

Running background processes:

To background a process, type an & at the end of the command line. 

eg. $ sleep 10
This will wait 10 seconds before returning the command prompt %. Until the command prompt is returned, you can do nothing except wait.

To run sleep in the background, type
eg. $ sleep 10 &

this command will returns job number and pid  something like this:
[1] 6650      
The & runs the job in the background and returns the prompt straight away, allowing you do run other programs while waiting for that one to finish.

The user is be notified of a job number (numbered from 1) enclosed in square brackets, together with a PID and is notified when a background process is finished. Backgrounding is useful for jobs which will take a long time to complete.


Backgrounding a current foreground process:

eg. $ sleep 1000

You can suspend the process running in the foreground by typing ^Z, i.e.hold down the [Ctrl] key and type [z]. Then to put it in the background, type

$ bg

3.4 Killing a process

kill (terminate or signal a process):

It is sometimes necessary to kill a process (for example, when an executing program is in an infinite loop).

To kill a job running in the foreground, type ^C (control c).

$ sleep 100
^c

To kill a suspended or background process, 

$ kill jobnumber


ps (process status):

Alternatively, processes can be killed by finding their process numbers (PIDs) and using kill PID_number


If a process refuses to be killed, uses the -9 option, i.e. type
eg. $kill -9 20277