chap2 advance java

Post on 03-Apr-2018

237 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

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.

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.

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.

7/28/2019 chap2 advance java

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

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

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();

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.

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  

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

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 

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());

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();

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()));

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();

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

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

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

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);

}

}

}

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.

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.

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 .

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.

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");

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.

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.

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.

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

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);

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);

}

}

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 .

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 .

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();

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

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).

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.

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.

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.

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.

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.

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.

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.

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();

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.

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.

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();

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(“abc@yahoo.com"); 

set To address

message.setTo(“xyz@yahoo.com"); 

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(“one@yahoo.com"); 

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();

top related