Vous êtes sur la page 1sur 19

Advanced Java

Unit-2: Core Java


2.1 Introduction to Networking
“NETWORKING IS THE PRACTICE OF LINKING TWO OR MORE
COMPUTING DEVICES TOGETHER FOR THE PURPOSE OF SHARING
DATA.”

There are two network architectures widely used today:


 peer-to-peer and
 client/server

In peer-to-peer networks each workstation has the same capabilities and


responsibilities. These networks are usually less expensive and simpler to
design than client/server networks, but they do not offer the same
performance with heavy traffic.

Peer to peer networks share responsibility for processing data among all of
the connected devices. Peer-to-peer networking (also known simply as peer
networking) differs from client-server networking in several respects.

The term client/server refers to a model utilizing networked client and server
computers and application software. Web, FTP, email, DNS and many other
database applications are client-server systems.

Client/Server Network

2.2 Basic Concepts of Networking


Writing a network program requires the various concepts as follows:

 Communication protocols : TCP & UDP


 Ports & Internet Addresses.
 Sockets
 URL (Uniform Resource Locator)
 Streams.
 Classes in java.io and java.net packages.

1 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

2.2.1 Transmission Control Protocol (TCP)


TCP is one of the main protocols in TCP/IP networks. TCP enables
two hosts to establish a connection and exchange streams of data.

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

2.2.2 User Datagram Protocol (UDP)


UDP (User Datagram Protocol) is a communications protocol that offers a
limited amount of service when messages are exchanged between computers
in a network that uses the Internet Protocol (IP).

UDP is also an alternative protocol for sending the data.

UDP uses the Internet Protocol to actually get a data unit (called a datagram)
from one computer to another. Unlike TCP, however, UDP does not provide
the service of dividing a message into packets (datagrams) and reassembling
it at the other end. Specifically, UDP doesn't provide sequencing of the
packets that the data arrives in. This means that the application program
that uses UDP must be able to make sure that the entire message has arrived
and is in the right order.

UDP provides two services not provided by the IP layer. It provides port
numbers to help distinguish different user requests and, optionally, a
checksum capability to verify that the data arrived intact.

It is an unreliable protocol that does not guarantee the arrival of packets at


their destination.

It does not guarantee the delivery of packets in the correct order.

Classes supported in java.net: DatagramPacket, DatagramSocket.

 DatagramPacket class stuffs bytes of data into UDP packets called


datagram.
 DatagramSocket sends as well as receive UDP datagram.

2 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

2.2.3 Ports
A port is application-specific or process-specific software construct serving as
a communications endpoint used by Transport layer protocols of the Internet
protocol suite, such as Transmission Control Protocol (TCP) and User
Datagram Protocol (UDP). A specific port is identified by its number,
commonly known as the port number, the IP address it is associated with,
and the protocol used for communication.

Each port from the server can be treated by clients as a separate machine
offering different services.

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

2.2.4 Internet Addressing


UDP (User Datagram Protocol) is a communications protocol that offers a
limited amount of service when messages are exchanged between computers
in a network that uses the Internet Protocol (IP).

IP address is a unique number for identifying a device like 137.92.11.13

The host name & IP address is represented by java.net.InetAddress

3 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

Its methods include:

InetAddress getByName(String host)


String getHostName();

2.3 Connecting to a Server


If you are a client, you need an API (Application Programming Interface) that
will allow you to send messages to that service & read replies from it.

If you are a server, you need to be able to create a port & listen at it.

You need to be able to read the messages that come in & reply to it.

The Socket & ServerSocket are client & server classes used for the purpose.

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

If everything goes well, the server accepts the connection. Upon acceptance,
the server gets a new socket bounds to a different port. It needs a new socket
so that it can continue to listen to the original socket for connection requests
while serving the connected client.

2.3.2 Socket and ServerSocket Classes


A socket is an endpoint of a two-way communication link between two
programs running on the network.

4 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

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

Java‟s „.net‟ package provides two classes:

a) Socket – for implementing a client


b) ServerSocket – for implementing a server

2.4 Implementing a Client


Step 1: Open a socket, which is an abstraction for the network software that
enables communication out of & into the program.

Pass the remote address & the port number to the socket
constructor.

Socket client = new Socket(“hostname”, portnumber);

If the connection fails, then an UnknownHostException is thrown.

Step 2: Create Output stream that can be used to send information to the
server.

PrintWriter prints each line out to standard output.

PrintWriter out = new


PrintWriter(client.getOutputStream());

Step 3: Create Input Stream to read the response from server.

BufferedReader in = new BufferedReader(


new InputStreamReader(client.getInputStream()));

Step 4: Close the socket when done:

client.close();

2.5 Implementing a Server


A sever is the one who sends information to clients. Once you start the server
program, it waits for some client to attach to its port. We can choose any port
number, which is not used by any of the standard services. The ServerSocket
class establishes a socket.

Every server program, such as an HTTP web server, continues performing


this loop:

5 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

a) It receives a command from the client through an Incoming data


stream.
b) It somehow fetches the information.
c) It sends the information to the client through the outgoing data
stream.

Step 1: This command establishes a server that monitors some port number.

ServerSocket listenSocket = new ServerSocket(portNumber);

Step 2: This command 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.

Socket server = listenSocket.accept();

Step 3: You can use this object to get input stream.

Input stream is used to get input from the client.

BufferedReader in = new BufferedReader(new


InputStreamReader(server.getInputStream()));

Step 4: You can use this object to get output stream.


Output stream is used to send information back to the client.

PrintWriter out = new PrintWriter(server.getOutputStream)));

Step 5: Close the Socket

Server.close();

2.6 Program for Client/Server Communication


Client.java

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

public class client


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

6 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

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=new
InputStreamReader(server.getInputStream());
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);
}
}
}

Server.java

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

public class server


{
public static void main(String s[])
{
ServerSocket sc;
Socket client;
DataInputStream d;
PrintStream toClient;
BufferedReader fromClient;
String str="";
try
{
d=new DataInputStream(System.in);
sc=new ServerSocket(1096);
System.out.println("ServerStarted");

7 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

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

2.7 Sending E-mail


To send an email, you need to make a socket connection to port 25, the SMTP
port.

Simple Mail Transport Protocol (SMTP) is the network protocol used to


send email across the Internet. SMTP describes the format for e mail
messages. SMTP is generally used to send messages from a mail client to a
mail server. You can connect to any server that runs an SMTP service.

On UNIX machines, that service is typically implemented by the sendmail


daemon. However, the server must be willing to accept your request. It is
used to be that sendmail servers were routinely willing to route e-mail for
anyone, but in these days of spam floods, most servers now have built in
checks & accept requests only from users, domains or IP address ranges that
they trust. Most SMTP servers do not check the veracity of the information-
you may be able to supply any sender you like.

2.7.1 Steps for Sending an E-mail


This program simply sends the sequence of commands. It displays the
commands that it sends to the SMTP server & the response that it receives.

The communication with the mail server occurs in a separate thread so that
the user interface thread is not blocked when the program tries to connect to
the mail server.

8 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

Step 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 package contains the necessary classes


for generating an email message.

Step 2: Establishing a Connection:

To send email you must first establish a network connection to the


SMTP server.

Create a new Smtp instance using SMTP hostname as argument.

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

Establish connection using smtp.connect();

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

Set “Subject” of message:

message.setSubject("Hello!");

Set “Body” of message:

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

Set “Carbon-Copy” recipients:

message.setCc(“one@yahoo.com");

9 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

Step 4: Sending the Email:

Send the email message using:

smtp.send(message);

Step 5: Releasing the Connection:

Release SMTP server connection using:

smtp.disconnect();

2.8 Making URL Connections

2.8.1 URL?
URL is Uniform Resource Locator. It is a reference (an address) to a resource
on the web server.

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.

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 URL & URLConnection classes encapsulate much of the complexity of


retrieving information from a remote site.

The java.net package uses a class called URL to represent a URL address.

The resource name contains components:


a) Host Name: The name of the machine on which the resource lives.
b) Filename: The pathname to the file on the machine.
c) Port Number: The port number to which to connect.
d) Reference: identifies a specific location within a file.

10 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

2.8.2 Creating a URL


a) Absolute URL – An absolute URL contains all of the information
necessary to reach the resource.

URL u = new URL ("http://www.gmail.com/");

This URL object called an absolute URL.

b) Relative URL – A relative URL contains only enough information to


reach the resource relative to another URL.

For e.g., suppose u know two URLs at the Gmail site.

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

You can create URL objects for these pages relative to their common base
URL: http://www.gmail.com/pages/ like this:

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


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

2.8.3 URL Constructors


a) URL(String s)
Creates a URL object from the String representation.

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


Creates a URL object from the specified protocol, host, port number, and
file.

c) URL(String protocol, String host, String file)


Creates a URL from the specified protocol name, hostname, and file name.

2.8.4 URL Methods


a) getContent()

Gets the contents of this URL

b) getFile()

Gets the file name of this URL.

11 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

c) getHost()

Gets the host name of this URL

d) getPort()

Gets the port number of this URL.

e) getProtocol()

Gets the protocol name of this URL.

f) openConnection()

Represents a connection to the remote object referred by URL.

g) openStream()

If you want to fetch the contents of the resource, then you can use the
openStream method of the URL class.

2.8.5 URL Connections


If you want additional information about a web resource, then you should use
the URLConnection class, which gives you much more control then the basic
URL class.

Once you have successfully created an instance of the URL class, you can
begin to call operations on it.

a) Open a connection, so that u can access the resource represented by


the URL.

b) On successfully connecting, it returns an instance of the


URLConnection class.

When working with a URLConnection object, you schedule your steps as


follows:

Step 1: Call the OpenConnection method of the URL class to obtain the
URLConnection object.

URLConnection connection = url.openConnection();

Step 2: Set any request properties, using the methods:


a) setDoInput
If DoInput is true, then the user can receive input from the
URLConnection.

12 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

b) setDoOutput
If DoOutput is true, then the user can receive input from the
URLConnection.

c) setIfModifiedSince
The ifModifiedSince property configures this URLConnection to
fetch only data that have been modified since a given time.

d) setUseCaches
If useCaches is true, then data can be retrieved from a local
cache.

e) setRequestProperty
Sets a request header field.

f) setReadTimeout
Set the timeout for reading data.

g) setConnectTimeout
Set the timeout for the connection.

Step 3: Connect to the remote resource by calling the connect method.

connection.connect();

Step 4: After connecting to the server, you can query the header information,
the following methods query standard fields:

a) getContentType
b) getContentLength
c) getContentEncoding
d) getDate
e) getExpiration
f) getLastModified

Step 5: Finally, you can access the resource data. Use the getInputStream
method to obtain an input stream for reading the information.

2.8.6 Opening a URL Connection


try
{
URL url = new URL("http://www.yahoo.com");
URLConnection connection = url.openConnection();
}
catch (MalformedURLException e)
{
System.out.println(e);
}

13 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

2.8.7 Reading From a URL


Once you have a successful connection, you can retrieve the input stream for
the connection and begin reading.

java.io classes operate on data returned from 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.

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

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

2.8.8 Writing to a URL


On successful connection, you can retrieve the output stream for the
connection and begin writing.
Many HTML pages contain forms-- text fields and other GUI objects that let
you enter data to send to the server.
After you type in the required information and initiate the query by clicking a
button, your Web browser writes the data to the URL over the network .

14 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

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 request and 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
property to true using the setDoOutput() method .

Eg: Writing to a URL

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

public class URLWriter


{
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();
ObjectOutputStream objectStream = new ObjectOutputStream(outStream);

objectStream.writeInt(54367);
objectStream.writeObject("Hello there");

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

2.8.9 URI (Uniform Resource Identifier)


A URI is a purely syntactical construct that specifies
the various parts of the string ,specifying a web resource.A URL is a special
kind of URI,namely,one with sufficient information to locate a resource.In the
java library,the URI class has no methods for accessing
the resource that the identifier specifies-its only purpose is parsing.In
contrast the URL class can open a stream
to the resource.For that reason the URL class only works
with schemas that the java library knows how to handle, such as http:,
https:,ftp:, & JAR files.

A URI has the syntax:


[scheme:]schemeSpecificPart [ #fragment]

15 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

here […...] denotes an optional part, & the : and # are included literally in the
identifier.
If the scheme: part is present,the URI is called absolute.
Otherwise it is called relative.

One of the purpose of the URI class is to parse an identifier & break it up into
its various components.
You can retrieve them with the methods:
a) getScheme
b) getSchemeSpecificPart
c) getAuthority
d) getUserInfo
e) getHost
f) getPort
g) getPath
h) getQuery
i) getFragment

The other purpose of the URI class is the handling of absolute & relative
identifiers.if you have an absolute URI such as:

http://docs.mycompany.com/api/java/net/
ServerSocket.html

& a relative URI such as:

…../…./java/net/Socket.html#Socket()

then you can combine the two into an absolute URI:

http://docs.mycompany.com/api/java/net/
Socket.html#Socket()

This process is called resolving a relative URL.

16 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

2.9 Advanced SOCKET PROGRAMMING


It involves various standpoints as follows:

1) Socket Timeouts
2) Internet Addresses
3) Interruptible sockets
4) Half Close

2.9.1 Socket Timeouts


In real life programs, you don‟t just want to read from a socket, because the
read methods will block until data are available. If the host is unreachable,
then your application waits for a long time & you are at the mercy of the
underlying operating system to time out eventually. So to avoid this, u should
decide what timeout value is reasonable for your application. Then call the
setSoTimeout() method to set a timeout value (in milliseconds).

Socket s=new Socket (“host name”, port number);


s.setSoTimeout(10000); // timeout after 10 seconds.

If the timeout value has been set for a socket,then all subsequent read &
write operations throw a SocketTimeoutException when the timeout has been
reached before the operation has completed its work.You can catch that
exception & react to the timeout.

try {
Scanner in =new Scanner(s.getInputStream()) ;
String line= in.nextLine();

} catch( InterruptedIOException ex)


{
react to timeout
}

2.9.2 Internet Addresses


Each computer is identified by a unique number called an Internet address or
an IP address.

Bytes are separated by periods.

For example, address for www.yahoo.com is 152.2.21.2

The numerical host addresses that consist of four bytes such as


132.163.4.102.however you can use the InetAddress class if you need to
convert between host names & Internet addresses.

17 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

The java.net package supports IPv6 Internet addresses , provided the host
operating system does.

The static getByName method returns an InetAddress object of a host. For


eg:

InetAddress address=InetAddress.getByName(“www.yahoo.com”);

returns an InetAddress object that encapsulates the sequence of four bytes


with the getAddress method.

byte[] addressBytes =address.getAddress();

Some host names with a lot of traffic correspond to multiple Internet


addresses, to facilitate load balancing.

You can get all hosts with the getAllByName method.

InetAddress address = InetAddress.getLocalHost();

2.9.3 Interruptible Sockets


When you connect to a socket, the current thread blocks until the connection
has been established or timeout has elapsed. Similarly, when you read or
write data through a socket, the current thread blocks until the operation is
successful or has time out. In interactive applications, you would like to give
users an option to simply cancel a socket connection that does not producing
a result. However, if a thread blocks on an unresponsive socket, you cannot
unblock it by calling interrupt.

To interrupt a socket operation, you can use a SocketChannel, a feature of


java.nio package.

Open the SocketChannel like this:

SocketChannel channel = SocketChannel.open(new


InetSocketAddress(host, port));

A Channel does not have associated streams. Instead it has read & write
methods that make use of Buffer objects. These methods are declared in
interfaces ReadableByteChannel & WriteableByteChannel.

If you don‟t want to deal with buffers, you can use the Scanner class to read a
SocketChannel. Scanner has a constructor with a ReadableByteChannel
parameter.

Scanner in =new Scanner(channel);

To turn a channel into an output stream, use

18 Mohit Chowdhary(Deptt. of CSE)


Advanced Java

Channel.newOutputStream method.

OutputStream out=Channels.newOutputStream(channel);

Now whenever a thread is interrupted during an open, read & write, the
operation does not block but is terminated with an exception.

2.9.4 Half Close


When a client program sends a request to a server, the server needs to be
able to determine when the end of the request occurs. Other protocols
contain a header that specifies the size of the request data. Otherwise
indicating the end of the request data is harder than writing data to a file.
With a file, you had just closed the file at the end of the data. However, if u
close a socket, then u immediately disconnect from the server.

The Half Close overcomes this problem, by closing the output stream of a
socket, indicating to the server the end of request data, but keeps the input
stream open so that you can read the response.
The client side looks like this:

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”);
writer.flush();
socket.shutdownOutput();
while(in.hasNextLine() !=null)
{
String line= in.nextLine();
}
socket.close();

The server side simply reads input until the end of the input stream is
reached. This protocol is only useful for one shot services such as HTTP
where the client connects, issues a request, catches the response & then
disconnects.

19 Mohit Chowdhary(Deptt. of CSE)

Vous aimerez peut-être aussi