53
Unit-2 Networking By: Neha Aggarwal (Senior Lecturer CSE/IT) 1

chap2 advance java

Embed Size (px)

Citation preview

Page 1: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 1/53

Unit-2

Networking

By:

Neha Aggarwal

(Senior Lecturer CSE/IT)

1

Page 2: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 2/53

2

Network 

a client, a server, and network 

ClientServer 

Client machine

Server machine

Client Server Communication

Page 3: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 3/53

3

For Writing a Network Program U

Need :

Communication protocols : TCP & UDP

Ports & Internet Addresses.

Sockets URL (Uniform Resource Locator)

Streams.

Classes in java.io and java.netpackages.

Page 4: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 4/53

4

TCP (Transmission Control Protocol)

Provides the ability to acknowledge receipt of 

IP packets & request of retransmission of lost

packets.

Allows the received packets to be put back

together in the order they were sent.

Supported classes in java.net : URL,URLConnection, Socket & ServerSocket.

Page 5: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 5/53

5

UDP (User Datagram Protocol)

Is also an alternative protocol for sending data .

Is an unreliable protocol that does not guaranteethat packets will arrive at their destination.

Does not guarantee that packets are delivered inthe correct order.

Classes supported in java.net : DatagramPacket,DatagramSocket.

DatagramPacket class stuffs bytes of data intoUDP packets calles datagrams.

DatagramSocket sends as well as receive UDPdatagrams.

Page 6: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 6/53

Page 7: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 7/537

Ports

Port numbers are represented by 16-bit

numbers(0 to 65,535).

Port numbers ranging from 0 to 1023 are

reserved for well known services like :

SMTP – 25 FTP – 21

Page 8: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 8/538

Internet Addressing

IP address is a unique number for identifying

a device like 137.92.11.13

The host name & IP address is representedby java.net.InetAddress

Its methods include:

InetAddress getByName(String host) String getHostName();

Page 9: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 9/539

Socket

If u are a client ,u need an API that willallow u to send messages to that service& read replies from it.

if u are a server, u need to be able tocreate a port & listen at it.

u need to be able to read the messages

that comes in & reply to it. The Socket & ServerSocket are client &

server classes to do this.

Page 10: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 10/5310

Socket Communication

 A server runs on a specific computer and

has a socket that is bound to a specific

port. The server waits and listens to the

socket for a client to make a connection

request.

server Client

Connection request p or  t  

Page 11: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 11/5311

Socket Communication

If everything goes well, the server accepts theconnection. Upon acceptance, the server gets a newsocket bounds to a different port. It needs a new socketso that it can continue to listen to the original socket for 

connection requests while serving the connected client.

server 

Client

Connection

 p

 or  t  

port   p  o  r   t

Page 12: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 12/5312

Sockets and Java Socket Classes

 A socket is an endpoint of a two-waycommunication link between twoprograms running on the network.

 A socket is bound to a port number sothat the TCP layer can identify theapplication that data destined to be sent.

Java’s .net package provides twoclasses:

Socket – for implementing a client

ServerSocket – for implementing a server 

Page 13: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 13/53

13

Implementing a Client

1. Create a Socket Object:

Socket client = new

Socket(“hostname”, portnumber);

2. Create Output stream that can be used tosend information to the server. 

PrintWriter out = new PrintWriter

(client.getOutputStream());

Page 14: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 14/53

14

Implementing a Client

3. Create Input Stream to read the

response from server 

BufferedReader in = new

BufferedReader(new

InputStreamReader(client.getIn

putStream()));

4. Close the socket when done:

client.close();

Page 15: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 15/53

15

Implementing a Server 

1. Create a ServerSocket object . ServerSocket listenSocket= new

ServerSocket(portNumber);

2. Create Socket object from 

ServerSocket

Socket server=listenSocket.accept();

3. Create Input Stream to read client Input 

BufferedReader in = newBufferedReader(new InputStreamReader

(server.getInputStream()));

Page 16: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 16/53

16

Implementing a Server 

4. Create Output streamused to send info back to

client

PrintWriter out = new PrintWriter

(server.getOutputStream)));

5. Close the Socket

Server.close();

Page 17: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 17/53

17

import java.io.*; import java.net.*;

public class cli {

public static void main(String s[] )

{

try

{

Socket server;

String str="";

 

DataInputStream d=new DataInputStream(System.in);

PrintStream toserver; BufferedReader fromserver;

server=new Socket("192.168.0.66",1096);

InputStreamReader isr=newInputStreamReader(server.getInputStream());

 

Client Server Program

Page 18: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 18/53

18

fromserver= new BufferedReader(isr); toserver=new PrintStream(server.getOutputStream());

while(true)

{

str=":"+d.readLine();

toserver.println(str); str=fromserver.readLine();

System.out.println(str);

}

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Client Server Program

Page 19: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 19/53

19

Serve.java import java.io.*;

import java.net.*;

public class serve

{

public static void main(String s[]) {

ServerSocket sc;

Socket client;

DataInputStream d;

PrintStream toClient;

BufferedReader fromClient;

String str="";

try

{

d=new DataInputStream(System.in);

 

Client Server Program

Page 20: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 20/53

20

Client Server Program

 sc=new ServerSocket(1096); System.out.println("ServerStarted");

client=sc.accept();

InputStreamReader isr=new InputStreamReader(client.getInputStream());

fromClient=new BufferedReader(isr);

toClient=new PrintStream(client.getOutputStream());

while(true)

{ str=fromClient.readLine();

System.out.println(str);

str=":"+d.readLine();

toClient.println(str);

}

} catch(Exception e)

{

System.out.println(e);

}

}

}

Page 21: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 21/53

21

URL

URL is Uniform Resource Locator.

It is a reference (an address) to a resource on the

web server.

 java.net package uses a class called URL torepresent a URL address.

 A URL takes the form of a string that describes

how to find a resource on the web server.

It consists of two main components: protocol

needed to access the resource and the location of 

the resource.

Page 22: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 22/53

22

URL

The protocol identifier indicates the name of 

the protocol to be used to fetch the

resource. The resource name is the

complete address to the resource.

The resource name contains components :

1) Host Name: The name of the machine

on which the resource lives.

Page 23: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 23/53

23

URL

2) Filename : The pathname to the fileon the machine.

3) Port Number :The port number towhich to connect .

4) Reference : identifies a specificlocation within a file .

Page 24: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 24/53

24

Creating a URL

•  Absolute URL -An absolute URL contains allof the information necessary to reach theresource.

URL u = new URL ("http://www.gmail.com/");This URL object called an absolute URL.

• Relative URL – A relative URL contains only

enough information to reach the resourcerelative to another URL.

• Eg: suppose u know two URLs at the Gmail

site.

Page 25: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 25/53

25

RELATIVE URL

http://www.gmail.com/pages/Gmail.login.html 

http://www.gmail.com/pages/Gmail.first.html 

U can create URL objects for these pages relative

to their common base URL:http://www.gmail.com/pages/ like this:

URL gmail = newURL("http://www.gmail.com/pages/");

URL gmailLogin = new URL(gmail,"Gmail.login.html");

URL gmailFirst = new URL(gmail,"Gmail.first.html");

Page 26: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 26/53

26

Constructors

1) URL(String s)

Creates a URL object from the Stringrepresentation.

2) URL(String protocol, String host, int port,String file)

Creates a URL object from the specified

protocol, host, port number, and file.3) URL(String protocol, String host, String file)

Creates a URL from the specified protocolname, host name, and file name.

Page 28: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 28/53

28

Methods

5) getProtocol()Gets the protocol name of this URL.

6) openConnection()

represents a connection to the remoteobject referred by URL.

7) openStream()

returns an InputStream for reading fromthat connection.

Page 29: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 29/53

29

URL CONNECTION

Once you have successfully created aninstance of the URL class, you can begin

to call operations on it.

1) open a connection, so that u can accessthe resource represented by the URL.

2) On successfully connected, it returns an

instance of the URLConnection class.

Page 31: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 31/53

31

Reading From a URL

Once you have a successful connection,ucan retrieve the input stream for the

connection and begin reading.

java.io classes operate on data returnedfrom URLConnection streams.

openStream() method get a stream from

which you can read the contents of the URL. The openStream() method returns a

 java.io.InputStream object

Page 32: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 32/53

32

Eg: Reading From a URL

import java.net.*;import java.io.*;

public class URLReader {

public static void main(String args[])try 

{

URL url = new 

URL("http://www.yahoo.com");URLConnection connection =url.openConnection();

connection.setDoInput(true);

Page 33: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 33/53

33

Eg: Reading From a URL

InputStream in =connection.getInputStream();

BufferedReader  b = new BufferedReader (new InputStreamReader (in));

String line = "";while ((line = b.readLine()) != null)

System.out.println(line);

b.close();

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

}

}

Page 34: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 34/53

34

Writing to a URL

successful connection, you can retrieve theoutput stream for the connection and begin

writing.

Many HTML pages contain forms-- text fieldsand other GUI objects that let you enter data

to send to the server.

After you type in the required informationand initiate the query by clicking a button,

your Web browser writes the data to the

URL over the network .

Page 35: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 35/53

35

Writing to a URL

 At the other end the server receives the data,processes it, and then sends you a response.

HTTP use POST method to send data to the

server. The server recognizes the POST requestand reads the data sent from the client.

Before retrieving and writing to a URLConnection

stream, you need to designate the connection as

being write-enabled by setting the Output propertyto true using the setDoOutput() method .

Page 36: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 36/53

36

Eg: Writing to a URL

import java.net.*;import java.io.*;

public static void main(String args[]) {

try {

URL url = new URL("http://www.yahoo.com");

URLConnection connection =

url.openConnection();connection.setDoOutput(true);

OutputStream outStream =connection.getOutputStream();

Page 38: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 38/53

38

 Advanced Socket Programming

Socket Timeouts

Internet Addresses

Interruptible sockets Half Close

Page 39: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 39/53

39

Socket Timeouts

• We use socket timeouts to deal withconnection errors.

If the host machine is unreachable then our 

application waits for a long time & your operating system times out u eventually.

So to avoid this, u should decide whattimeout value is reasonable for your application.

Call the setSoTimeout() method to set atimeout value (in milliseconds).

Page 40: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 40/53

40

Socket Timeouts

 Socket s=new Socket (“host name”, port

number);

s.setSoTimeout(10000);

It will throw SocketTimeoutException, whenthe timeout has been reached before the

operation has completed its work.

Page 41: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 41/53

41

Internet Addresses

Each computer is identified by a unique

number called an Internet address or an IP

address.

IP addresses are four bytes long, these are

referred to as IPv4 addresses.

Bytes are separated by periods.For 

example,address for www.yahoo.com is

152.2.21.2.

Page 42: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 42/53

42

InetAddress Class

U can use this class, if u need to convert

between host names & Internet addresses.

getByName() method returns an

InetAddress object of a host.

InetAddress

address=InetAddress.getByName(“www.yah

oo.com”); 

this returns an IP address of this host name.

Page 43: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 43/53

43

Interruptible Sockets

When u connect to a socket, current thread

blocks until the connection has been

established or timeout has elapsed.

If u want to give users an option to cancel a

socket connection that doesnot producing a

result, u will call interrupt.

To interrupt a socket operation, u will use a

SocketChannel, a feature of java.nio

package.

Page 44: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 44/53

44

Interruptible Sockets

1) Open the SocketChannel like this :

SocketChannel channel =

SocketChannel.open(new

InetSocketAddress(host, port)); SocketChannel has read & write methods that are

declared in interfaces ReadableByteChannel &

WriteableByteChannel.

We will use Scanner class to read a

SocketChannel .Scanner has a constructor with a

ReadableByteChannel parameter.

Page 45: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 45/53

45

Interruptible Sockets

2) Scanner in =new Scanner(channel);

3) To turn a channel into an output stream,use Channel.newOutputStream method.

OutputStream out=Channels.newOutputStream(channel);

Now whenever a thread is interrupted

during an open, read & write, theoperation doesnot block but is terminatedwith an exception.

Page 46: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 46/53

46

Half Close

When a client program sends a request to aserver, the server needs to be able to determinewhen the end of the request occurs (ends of writing of data to server).

Indicating the end of the request data is harder than writing data to a file.

If u close a socket, then u immediatelydisconnect from a server.

The Half Close overcomes this problem, byclosing the output stream of a socket, indicating tothe server the end of request data.

Page 47: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 47/53

47

Half Close

Socket s = new Socket (“host name”, port

number);

Scanner in = new Scanner 

(socket.getInputStream());

PrintWriter writer= new

PrintWriter(socket.getOutputStream());

 writer.print(“end of data”); 

socket.shutdownOutput();

Page 48: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 48/53

48

Sending Email

What is SMTP ?

Simple Mail Transport Protocol (SMTP) is

the network protocol used to send email

across the Internet.

SMTP is generally used to send messagesfrom a mail client to a mail server.

Page 49: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 49/53

49

Steps for Sending Email

1) Importing the necessary packages:

import com.jscape.inet.smtp.*;

Import com.jscape.inet.email.*;

The com.jscape.inet.smtp package contains

the necessary classes for communicating

with an SMTP server.

The com.jscape.inet.email packagecontains the necessary classes for 

generating an email message.

Page 50: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 50/53

50

Steps for Sending Email

2) Establishing a Connection :To send email you must first establish a

network connection to your SMTP server.

create a new Smtp instance using SMTPhostname as argument.

Smtp smtp = new Smtp("smtp.yahoo.com");

establish connection

smtp.connect();

Page 51: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 51/53

51

Steps for Sending Email

3) Composing the Email :

Create a new EmailMessage instance

EmailMessage message = new

EmailMessage();

set From address

message.setFrom(“[email protected]"); 

set To address

message.setTo(“[email protected]"); 

Page 52: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 52/53

52

Steps for Sending Email

set subject of messagemessage.setSubject("Hello!");

set body of message

message.setBody("Have a nice day");

set carbon-copy recipients

message.setCc(“[email protected]"); 

Page 53: chap2 advance java

7/28/2019 chap2 advance java

http://slidepdf.com/reader/full/chap2-advance-java 53/53

Steps for Sending Email

4) Sending the Email :

send the email message

smtp.send(message);

5) Releasing the Connection :

release SMTP server connection

smtp.disconnect();