0% found this document useful (0 votes)
17 views

Chapter 4

Uploaded by

varaddhadave01
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter 4

Uploaded by

varaddhadave01
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Advanced Java Programming

Archana Gopnarayan
Lecturer , Department of Information Technology (NBA Accrediated)
Vidyalankar Polytechnic
InetAddres
• The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address.

• InetAddress can handle both IPv4 and IPv6 addresses.


Factory Methods

static InetAddress getLocalHost( ) throws UnknownHostException

static InetAddress getByName(String hostName) throws UnknownHostException

static InetAddress[ ] getAllByName(String hostName) throws


UnknownHostException
Instance Method
• The InetAddress class has several other methods
• boolean equals(Object other) Returns true if this object has the same Internet
address as other.
• byte[ ] getAddress( ) Returns a byte array that represents the object’s IP address in
network byte order.
• String getHostAddress( ) Returns a string that represents the host address
associated with the InetAddress object.
• String getHostName( ) Returns a string that represents the host name associated
with the InetAddress object.
• boolean isMulticastAddress( ) Returns true if this address is a multicast address.
Otherwise, it returns false.
• String toString( ) Returns a string that lists the host name and the IP address for
convenience.
TCP/IP Client Sockets
• There are two kinds of TCP sockets in Java. One is for servers, and the other is for
clients.
• The ServerSocket class is designed to be a “listener,” which waits for clients to
connect before doing anything. Thus, ServerSocket is for servers.
• The Socket class is for clients.
• The creation of a Socket object implicitly establishes a connection between the
client and server.

Socket(String hostName, int port) throws UnknownHostException, IOException

Socket(InetAddress ipAddress, int port) throws IOException


• Socket defines several instance methods.
InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket
object. It returns null if the socket is not connected.

int getPort( ) Returns the remote port to which the invoking Socket object is connected. It
returns 0 if the socket is not connected.

int getLocalPort( ) Returns the local port to which the invoking Socket object is bound. It
returns –1 if the socket is not bound.
• We can gain access to the input and output streams associated with a Socket by
use of the getInputStream( ) and getOuptutStream( ) methods.

• Each can throw an IOException if the socket has been invalidated by a loss of
connection.
• These streams are used to send and receive data.

InputStream getInputStream( ) throws IOException


• Returns the InputStream associated with the invoking socket.

OutputStream getOutputStream( ) throws IOException


• Returns the OutputStream associated with the invoking socket.

• connect( ), which allows you to specify a new connection;


• isConnected( ), which returns true if the socket is connected to a server;
• isBound( ),which returns true if the socket is bound to an address;
• isClosed( ), which returns true if the socket is closed.
TCP/IP Server Sockets
• The ServerSocket class is used to create servers that listen for either local or
remote client programs to connect to them on published ports.
• When you create a ServerSocket, it will register itself with the system as having
an interest in client connections.
• The constructors for ServerSocket reflect the port number that you want to accept
connections on and, optionally, how long you want the queue for said port to be. The
queue length tells the system how many client connections it can leave pending
before it should simply refuse connections.
• The default is 50.
• ServerSocket(int port) throws IOException
Creates server socket on the specified port with a queue length of 50.
• ServerSocket(int port, int maxQueue) throws IOException
Creates a server socket on the specified port with a maximum queue length of
maxQueue.
• ServerSocket(int port, int maxQueue, InetAddress localAddress) throws
IOException
Creates a server socket on the specified port with a maximum queue length of
maxQueue. On a multihomed host, localAddress specifies the IP address to which
this socket binds.
URL
• Uniform Resource Locator
• A URL specification is based on four components.
• The first is the protocol to use, separated from the rest of the locator by a colon (:).
Common protocols are HTTP, FTP, gopher, and file, although these days almost
everything is being done via HTTP
• The second component is the host name or IP address of the host to use; this is
delimited on the left by double slashes (//) and on the right by a slash (/) or optionally
a colon (:).
• The third component, the port number, is an optional parameter, delimited on the
left from the host name by a colon (:) and on the right by a slash (/).
• The fourth part is the actual file path. Most HTTP servers will append a file named
index.html or index.htm
• Java’s URL class has several constructors; each can throw a
malformedURLException.

URL(String urlSpecifier) throws MalformedURLException

URL(String protocolName, String hostName, int port, String path) throws


MalformedURLException

URL(String protocolName, String hostName, String path) throws


MalformedURLException
import java.net.*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("http://www.google.com/downloads");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
URL Connection
• URLConnection is a general-purpose class for accessing the attributes of a
remote resource.
• Once you make a connection to a remote server, you can use URLConnection to
inspect the properties of the remote object before actually transporting it locally.

int getContentLength( ) Returns the size in bytes of the content associated with the
resource. If the length is unavailable, –1 is returned.
String getContentType( ) Returns the type of content found in the resource. Returns null
if the content type is not available.
long getDate( ) Returns the time and date of the response
long getExpiration( ) Returns the expiration time and date of the resource represented
in terms of milliseconds Zero is returned if the expiration date is unavailable.
Map<String, List<String>>getHeaderFields( ) Returns a map that contains all of the
header fields and values.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception
{
int c;
URL hp = new URL("http://www.internic.net");
URLConnection hpCon = hp.openConnection();
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
System.out.println("Content-Type: " + hpCon.getContentType());
d = hpCon.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
d = hpCon.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
int len = hpCon.getContentLength();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while (((c = input.read()) != -1))
{
System.out.print((char) c);
}
input.close();
}
else {
System.out.println("No content available.");
}
}
}
HttpURLConnection
• Java provides a subclass of URLConnection that provides support for HTTP
connections. This class is called HttpURLConnection.

• static boolean getFollowRedirects( ) Returns true if redirects are automatically followed


and false otherwise.

• String getRequestMethod( ) Returns a string representing how URL requests are made.
The default is GET. Other options, such as POST, are available.

• int getResponseCode( ) Returns the HTTP response code. –1 is returned if no response


code can be obtained. An IOException is thrown if the connection fails.

• String getResponseMessage( ) throws IOException Returns the response message


associated with the response code. Returns null if no message is available.
• static void setFollowRedirects(boolean how) If how is true, then redirects are
automatically followed. If how is false, redirects are not automatically followed. By default,
redirects are automatically followed.
• void setRequestMethod(String how) throws ProtocolException Sets the method by
which HTTP requests are made to that specified by how. The default method is GET, but
other options, such as POST, are available.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpURLDemo
{
public static void main(String args[]) throws Exception
{
URL hp = new URL("http://www.google.com");
HttpURLConnection hpCon = hp.openConnection();
System.out.println("Request method is " +hpCon.getRequestMethod());
System.out.println("Response code is " +hpCon.getResponseCode());
System.out.println("Response Message is " +hpCon.getResponseMessage());
Map<String, List<String>> hdrMap = hpCon.getHeaderFields();
Set<String> hdrField = hdrMap.keySet();
System.out.println("\nHere is the header:");
// Display all header keys and values.
for(String k : hdrField)
{
System.out.println("Key: " + k + " Value: " + hdrMap.get(k));
}
}
}
Datagrams
• Datagrams are bundles of information passed between machines.
• Java implements datagrams on top of the UDP protocol by using two classes:
• DatagramPacket object is the data container,
• DatagramSocket is the mechanism used to send or receive the DatagramPackets.
DatagramSocket class
• Java DatagramSocket class represents a connection-less socket for sending and
receiving datagram packets.
• A datagram is basically an information but there is no guarantee of its content, arrival
or arrival time.
DatagramSocket() throws SocketExeption
it creates a datagram socket and binds it with the available Port Number on the localhost
machine.
• DatagramSocket(int port) throws SocketExeption
it creates a datagram socket and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketEeption
it creates a datagram socket and binds it with the specified port number and host
address.
DatagramPacket class
• DatagramPacket is a message that can be sent or received.
DatagramPacket(byte[] data, int length): it creates a datagram packet.
This constructor is used to receive the packets.
• DatagramPacket(byte[] data, int length, InetAddress address, int port)
It creates a datagram packet. This constructor is used to send the packets.

You might also like