0% found this document useful (0 votes)
1 views26 pages

Unit 3 - Java Networking

Uploaded by

jiiimran666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views26 pages

Unit 3 - Java Networking

Uploaded by

jiiimran666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Java Networking

• Java Networking is a concept of connecting two or more computing


devices together so that we can share resources.
• Java socket programming provides facility to share data between
different computing devices.

• Advantage of Java Networking


• sharing resources
• centralize software management
Java Networking Terminology
The widely used java networking terminologies are given below:
1. IP Address
• IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
• It is a logical address that can be changed.
2. Protocol
• A protocol is a set of rules basically that is followed for communication. For example:
TCP, FTP, Telnet, SMTP, POP etc.
3. Port Number
• The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
• The port number is associated with the IP address for communication between two
applications.
4. MAC Address
• MAC (Media Access Control) Address is a unique identifier of NIC
(Network Interface Card). A network node can have multiple NIC but
each with unique MAC.
5. Connection-oriented and connection-less protocol
• In connection-oriented protocol, acknowledgement is sent by the
receiver, so it is a reliable protocol but it is a slow process. The
example of connection-oriented protocol is TCP.
• In connection-less protocol, acknowledgement is not sent by the
receiver. So it is not a reliable protocol but is has fast process. The
example of connection-less protocol is UDP.
6. Socket
A socket is an endpoint between two-way communication.
• Socket communication takes place via a protocol.
• Internet Protocol (IP) is a low-level routing protocol that breaks data
into small packets and sends them to an address across a network,
which does not guarantee to deliver said packets to the destination.
• Transmission Control Protocol (TCP) is a higher-level protocol that
manages data segments, sorting and retransmitting them as
necessary for the reliable data transmission.
• User Datagram Protocol (UDP), It is next to TCP and can be used
directly to support fast, connectionless, unreliable transport of data
segments.
• The notion of a socket allows a single computer to serve many different
clients at once, as well as serving many different types of information
• Once a connection has been established, a higher-level protocol ensures,
which is dependent on which port you are using. TCP/IP reserves the lower
1,024 ports for specific protocols called as reserved port
• TCP/IP has 65536 different TCP ports to which every machine can talk, few
of them are:
• Port name port number
• Echo 7
• Discard 9
• FTP 21
• telnet 23
• smtp 25
• http 80
• pop3 110
The Networking Classes and Interfaces

InetAddress

• The InetAddress class is used to encapsulate both the numerical IP address and
the domain name.

• The InetAddress class uses the name of an IP host, which is more convenient and
understandable than its IP address.

• InetAddress can handle both IPv4 and IPv6 addresses.


Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress
object, you have to use one of the available factory methods. Factory methods are
merely a convention whereby static methods in a class return an instance of that
class. This is done in lieu of overloading a constructor with various parameter lists
when having unique method names makes the results much clearer. Three
commonly used InetAddress factory methods are shown here:
Factory Methods
• static InetAddress getLocalHost( ) throws UnknownHostException -
returns the InetAddress object that represents the local host.
• static InetAddress getByName(String hostName) throws
UnknownHostException - returns an InetAddress for a host name
passed to it.
• static InetAddress[ ] getAllByName(String hostName) throws
UnknownHostException- returns an array of InetAddresses that
represent all of the addresses that a particular name resolves to.
• If these methods are unable to resolve the host name, they throw an
UnknownHostException.
Program:
InetAddress class demostration
import java.io.*;
import java.net.*;

public class InetAddressExample{


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

InetAddress ip = InetAddress.getByName("www.google.com");
System.out.println("Host Name " + ip.getHostName());
System.out.println("IP Address: " + ip.getHostAddress());
InetAddress ip2 = InetAddress.getLocalHost();
System.out.println("Local Host: "+ip2);
} catch (Exception e) {
System.out.println(e);
}
}
}
Java Socket Programming
• Java Socket programming is used for communication between the
applications running on different JRE.
• Java Socket programming can be connection-oriented or connection-
less.
• Socket and ServerSocket classes are used for connection-oriented
socket programming and DatagramSocket and DatagramPacket
classes are used for connection-less socket programming.
TCP/IP Sockets
• TCP/IP sockets are used to implement reliable, bidirectional, persistent,
point-to-point, stream-based connections between hosts on the Internet. A
socket can be used to connect Java’s I/O system to other programs that
may reside either on the local machine or on any other machine on the
Internet.
• 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. It is designed to connect to server sockets and initiate
protocol exchanges.
• The client in socket programming must know two information:
IP Address of Server, and Port number.
Socket Programming Architecture
Socket class
• A socket is simply an endpoint for communications between the
machines. The Socket class can be used to create a socket.
• Here are two constructors used to create client sockets:
Socket(String hostName, int port) throws Creates a socket connected to the named host
UnknownHostException, IOException and port.

Socket(InetAddress ipAddress, int port) Creates a socket using a preexisting InetAddress


throws IOException object and a port.
Socket class
• Important methods

Method Description

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.

public InputStream getInputStream() returns the InputStream attached with this socket.

public OutputStream getOutputStream() returns the OutputStream attached with this socket.

public synchronized void close() closes this socket


ServerSocket class
• The ServerSocket class can be used to create a server socket. This
object is used to establish communication with the clients.
• Here are two constructors used to create Server sockets:
ServerSocket(int port) throws IOException Creates a server socket on the specified port

ServerSocket(int port, int queue_length) Creates a server socket on the specified port
throws IOException with the specified queue length.
ServerSocket class
• Important methods

Method Description

public Socket accept() returns the socket and establish a connection between server
and client.
public synchronized void close() closes this socket
URL Class
• The URL provides a reasonably intelligible form to uniquely identify or
address information on the Internet. URLs are ubiquitous; every
browser uses them to identify information on the Web.

• The Java URL class represents an URL. URL is an acronym for Uniform
Resource Locator. It points to a resource on the World Wide Web. For
example:
http://egurutechnology.com:8880/login_up.php
http://egurutechnology.com:8880/login_up.php

• A URL specification is based on four components.


• Protocol: In this case, http is the protocol.
• Server name or IP Address: In this case, egurutechnology.com is the
server name.
• Port Number: It is an optional attribute. If we write 8880 is the port
number. If port number is not mentioned in the URL, it returns -1.
• File Name or directory name: In this case, login_up.php is the file
name.
URL Class Constructor
• Java’s URL class has several constructors; each can throw a
MalformedURLException.

• URL(String urlSpecifier) throws MalformedURLException

The next two forms of the constructor allow you to break up the URL
into its component parts:
• URL(String protocolName, String hostName, int port, String path)
throws MalformedURLException
• URL(String protocolName, String hostName, String path) throws
MalformedURLException
URL class methods
• The java.net.URL class provides many methods. The important
methods of URL class are given below.
Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public URLConnection openConnection() it returns the instance of URLConnection i.e.


associated with this URL.
URLConnection class
• 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.

• to get the object of URLConnection class The openConnection()


method of URL class returns the object of URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
URLConnection methods
• URLConnection defines several methods.
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. This is the value
of the content-type header field. Returns null if the content type is
not available.
long getDate( ) Returns the time and date of the response represented in terms of
milliseconds since January 1, 1970 GMT.
long getExpiration( ) Returns the expiration time and date of the resource represented in
terms of milliseconds since January 1, 1970 GMT. Zero is returned if
the expiration date is unavailable.
long getLastModified( ) Returns the time and date, represented in terms of milliseconds
since January 1, 1970 GMT, of the last modification of the resource.
Zero is returned if the last-modified date is unavailable.
Java DatagramSocket and DatagramPacket
• Java DatagramSocket and DatagramPacket classes are used for connection-
less socket programming.

What Is a Datagram?
• A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.

• Applications that communicate via datagrams send and receive completely


independent packets of information. These clients and servers do not have
and do not need a dedicated point-to-point channel. The delivery of
datagrams to their destinations is not guaranteed. Nor is the order of their
arrival.
DatagramSocket class Constructor
• DatagramSocket() throws SocketException: it creates a datagram
socket and binds it with the available Port Number on the localhost
machine.
• DatagramSocket(int port) throws SocketException: it creates a
datagram socket and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws
SocketException: it creates a datagram socket and binds it with the
specified port number and host address.
DatagramPacket class constructor
• DatagramPacket(byte[] barr, int length): it creates a datagram
packet. This constructor is used to receive the packets.

• DatagramPacket(byte[] barr, int length, InetAddress address, int


port): it creates a datagram packet. This constructor is used to send
the packets.

You might also like