networking & socket programming in java

18
NETWORKING IN JAVA AN EFFORT BY:- ANKUR AGRAWAL B.TECH(CSE 5 th SEM)

Upload: ankur-agrawal

Post on 18-Nov-2014

4.274 views

Category:

Technology


3 download

DESCRIPTION

This is my effort to help you people understand how real networking is achieved in java using Socket programming.

TRANSCRIPT

Page 1: Networking & Socket Programming In Java

NETWORKING IN JAVA

AN EFFORT BY:-

ANKUR AGRAWALB.TECH(CSE 5th SEM)

Page 2: Networking & Socket Programming In Java

TCP & UDPTCP(TRANSMISSION CONTROL PROTOCOL)

TCP is a connection-based protocol that provides a reliable flow of data between two computers.e.g. : Telephone call. Web browsing. UDP(USER DATAGRAM PROTOCOL)

UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.e.g.: ping command.

Page 3: Networking & Socket Programming In Java

PORT

Ports are identified by a 16-bit number. The TCP and UDP protocols use PORTS to map incoming data to a particular process running on a computer.

Page 4: Networking & Socket Programming In Java

INTERNET ADDRESSING & DNS(DOMAIN NAME SYSTEM)

Every computer on a network is known by a unique number which is known as IP Address. Generally we use IPV4 which consists of 4 BYTES.(e.g. 172.17.167.4)etc.

Websites have both a friendly address, called a URL, and an IP address. People use URLs to find websites, but computers use IP addresses to find websites. DNS translates URLs into IP addresses (and vice versa).

Page 5: Networking & Socket Programming In Java

NETWORKING CLASSES(java.net PACKAGE)

InetAddress:-This class is used to encapsulate both the numerical IP address and the domain name for that address.To create an InetAddress object we have to use one of the available factory methods:-1.static InetAddress getLocalHost( )throws UnknownHostException2.static InetAddress getByName(String hostName)throws UnknownHostException3.static InetAddress[ ] getAllByName(String hostName)throws UnknownHostException

Page 6: Networking & Socket Programming In Java

import java.net.*; public class prog1 {

public static void main(String args[])throws UnknownHostException{InetAddress in;in=InetAddress.getLocalHost();System.out.println("local host name="+in);in=InetAddress.getByName("www.google.com");System.out.println("ip of google::"+in);InetAddress dn[]=InetAddress.getAllByName("www.google.com");System.out.println("ALL NAMES FOR GOOGLE");for(int i=0;i<dn.length;i++)System.out.println(dn[i]);}

}

PROGRAM TO ILLUSTRATE InetAddress

Page 7: Networking & Socket Programming In Java

URL:-URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.

http://www.google.com:80/index.htm

PROTOCOL IDENTIFIER RESOURCE NAME

CONSTRUCTOR:-1.URL(String urlSpecifier)2.URL(String protocolName, String hostName, int port, String path)3.URL(String protocolName, String hostName, String path) All of these constructor throws MalformedURLException.

Page 8: Networking & Socket Programming In Java

PROGRAM TO ILLUSTRATE URL import java.io.*; import java.net.*; public class prog2 { public static void main(String args[])throws MalformedURLException

{URL u=new URL("http://www.google.com:80/index.htm");System.out.println("HOST NAME="+u.getHost());System.out.println("PORT ="+u.getPort());System.out.println("PROTOCOL="+u.getProtocol());System.out.println("PATH="+u.getFile());

} }

Page 9: Networking & Socket Programming In Java

THE openStream() methodIt is used for directly reading from a URL.

import java.net.*; import java.io.*; public class prog3{

public static void main(String[] args) throws Exception {

URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null)

System.out.println(inputLine); In.close();

} }

Page 10: Networking & Socket Programming In Java

READING FROM A URL THROUGH URLConnection OBJECT

We can create URLConnection object using the openConnection() method of URL object.

import java.net.*; import java.io.*; public class prog4{ public static void main(String[ ] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/");

URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); } }

Page 11: Networking & Socket Programming In Java

SOCKET PROGRAMMING

1. URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application.

2. The communication that occurs between the client and the server must be reliable.

3. TCP provides a reliable, point-to-point communication channel .

4. To communicate over TCP, a client program and a server program establish a connection to one another.

5. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection.

Page 12: Networking & Socket Programming In Java

WHAT IS A SOCKETA socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

In java.net package there are two classes for socket purpose.1.Socket2.ServerSocket

We can initialize a Socket object using following constructor–Socket(String hostName, int port)

We can initialize a ServerSocket object using following constructor-ServerSocket s = new ServerSocket(port no.)It will establishes a server that monitors port no.

Page 13: Networking & Socket Programming In Java

13

Java SocketsJava SocketsServerSocket(1234)

Socket(“128.250.25.158”, 1234)

Output/write stream

Input/read stream

It can be host_name like “mandroo.cs.mu.oz.au”

Client

Server

Page 14: Networking & Socket Programming In Java

LET’S DEAL WITH ServerSocket CLASS

accept():-ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to initiate communications, and then return with a normal Socket that is then used for communication with the client.

e.g. ServerSocket s=new ServerSocket(8189); establishes a server that monitors port 8189. The command

Socket sp = s.accept();tells the program to wait indefinitely until a client connects to that port. Once someone connects to this port by sending the correct request over the network, this method returns a Socket object that represents the connection that was made.

Page 15: Networking & Socket Programming In Java

import java.io.*; import java.net.*; import java.util.*; public class prog5 { public static void main(String args[])throws

Exception {ServerSocket s=new ServerSocket(8120);System.out.println(“SERVER IS WAITING FOR THE CLIENTS TO BE CONNECTED…..”);while(true){Socket sp=s.accept(); Scanner in=new Scanner(sp.getInputStream());

PrintWriter out=newPrintWriter(sp.getOutputStream(),true);

out.println("WRITE STH. WRITE BYE TO EXIT ");

boolean f=true;While(f==true &&

(in.hasNextLine())==true){String line=in.nextline();If((line.trim()).equals(“BYE")){ f=false;break;}elseout.Println("echo::"+line)}Sp.Close();}}

}

PROGRAM 1:- IMPLEMENTING SERVER SOCKET AND COMMUNICATION BETWEEN CLIENT AND SERVER.(THERE IS ONLY ONE CLIENT AT A TIME)IF MORE THAN 1 CLIENT WANT TO COMMUNIACATE THEN THEY HAVE TO WAIT TILL ONE FINISHES.

Page 16: Networking & Socket Programming In Java

PROG2:-COMMUNIACTION BETWEEN MULTIPLE CLIENTS AND A SERVER USING SOCKETS SIMULTANEOUSLY(no need to wait).(ServerSocket)import java.io.*;

import java.net.*;import java.util.*;public class prog6{

public static void main(String args[]) throws Exception{

int i=1;ServerSocket s=new ServerSocket(8120);System.out.println("\n SERVER WAITS FOR THE CLIENTS TO

BE CONNECTED...........");while(true){

Socket sp=s.accept();System.out.println("\nclient no."+i+"connected\n");Runnable r=new netthread(sp,i);Thread t=new Thread(r);t.start(); // it begins the execution of thread beginning

at the run() method i++;

}}

}

Page 17: Networking & Socket Programming In Java

class netthread implements Runnable{

Socket soc;int cl;public netthread(Socket k,int j){

soc=k;cl=j;

}public void run() {try{ try {

Scanner in=new Scanner(soc.getInputStream());

PrintWriter out=new PrintWriter(soc.getOutputStream(),true);

out.println("WRITE STH. WRITE BYE TO EXIT ");

Boolean f=true;while(f==true && in.hasNextLine()==true)

{String

line=in.nextLine();

if(line.trim().equals("BYE"))

{f=false;

break; }

elseout.println("ECHO::"+line);

} } finally

{soc.close();System.out.println("CLIENT

NO."+cl+"DISCONNECTED"); }

}catch(IOException e){ System.out.println(e);}}

}

Page 18: Networking & Socket Programming In Java