Advance Java Unit 4 Networking Basics Prof Akhil Jaiswal Notes - No
Advance Java Unit 4 Networking Basics Prof Akhil Jaiswal Notes - No
Networking: Networking is the exchange of information between computers. Networking often begins
with a single point of common ground. The network is the soul of Java. Most of what is interesting about
Java centre’s on the potential for dynamic, networked applications. As Java’s networking API’s have
matured, Java has also become the language of choice for implementing traditional client/server
applications and services.
Socket: A socket identifies an endpoint in a network between two machines. A socket refers to a special
object that is used for establishing connection between the client and server computers. The socket
paradigm was part of the UNIX release in the early 1980s. Sockets are at the foundation of modern
networking because a socket allows a single computer to serve many different clients at once, as well as to
serve many different types of information. This is accomplished through the use of a port, which is a
numbered socket on a particular machine.
Socket
A socket is used for connecting I/O system of Java with other programs that reside either on the
local machine or on any other machine on the Internet. Sockets are a low-level programming interface for
networked communications. They send streams of data between applications that may or may not be on
the same host.
Sockets originated in BSD Unix and are, in some programming languages, hairy, complicated. The
reason for this is that most socket APIs can be used with almost any kind of underlying network protocol.
Since the protocols that transport data across the network can have radically different features, the socket
interface can be quite complex.
1. 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.
2. Transmission Control Protocol (TCP) : is a higher-level protocol that manages to robustly string
together these packets, sorting and retransmitting them as necessary to reliably transmit data. A third
protocol
3. User Datagram Protocol (UDP) : sits next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.
Reserved Sockets: TCP and UDP supports 64K sockets, from socket number 0 to socket number 65,535.
You should select a port number by keeping in mind that, cocket number between 0 to 1023 are reserved
for popular application protocols (e.g., Port 80 for HTTP, Port 443 for HTTPS, Port 21 for FTP, Port 23 for
Telnet, Port 25 for SMTP, Port 110 for POP3, etc.). Port number on and above 1024 are available for your
testing.
Client/Server:
In Networking, commonly the communication takes place between clients and servers. The side
that initiates the conversation is usually considered the client. The side that accepts & serves the request
is usually the server. In the case where two peer applications use sockets to talk.
Clients use the port number assigned to the service they want to access. If you think of the host
computers as hotels and the applications as guests, the ports are like the guests room numbers. For one
person to call another, he or she must know the other party’s hotel name and room number.
Proxy server is an intermediary server between client and the internet. Proxy servers offer the
following basic functionalities: Firewall and network data filtering, Network connection sharing, Data
caching. Proxy servers allow hiding, concealing and making network id unidentified by hiding your IP
address. All traffic that originates from the client, is sent to the proxy server and the proxy server makes
requests to the remote server on the client’s behalf. Once the proxy server receives the required files, it
then forwards them on to the client.
Internet address: A key component of the Internet is the address. Every computer on the Internet has
one Address to reach out from other systems. An Internet address is a number that uniquely identifies
each computer on the Network. Originally, all Internet addresses consisted of 32-bit values, organized
as four 8-bit values. Earlier, this address type was specified by IPv4 (Internet Protocol, version 4).
However, a new addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6
uses a 128-bit value to represent an address, organized into eight 16-bit chunks.
Example:
IPV4 address: 12.244.233.165 (32-bit)
IPV6 address: 2001:0db8:0000:0000:0000:ff00:0042:7879 (128-bit)
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. The client in socket programming must know
two information:
Here, in Figure below shows Socket Application Programming Interface (API) where there is one-way
client and server communication. In this application, client sends a message to the server, server reads the
message and prints it. Here, two classes are being used: Socket and ServerSocket. The Socket class is used
to communicate client and server. Through this class, we can read and write message. The ServerSocket
class is used at server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at server-side.
Socket class: A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket that provides useful methods given below:
Important methods:
Method Description
1) public InputStream getInputStream() returns the InputStream data attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream data attached with this socket.
Important methods
Method Description
1) public Socket accept() returns socket and establish a connection between server & client.
Java DataInputStream readUTF() Method: The readUTF method of DataInputStream class reads a
string that has been encoded using a modified UTF-8 (Unicode Transformation Format – 8-bit) format & returned
a String.
String readUTF(DataInput in);
Creating Server: To create the server application, we need to create the instance of ServerSocket class.
Here, we are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with the given
port number, it returns an instance of Socket.
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass the
IP address or hostname of the Server and a port number. Here, we are using "localhost" because our
server is running on same system.
Let's see a simple of Java socket programming where client sends a text and server receives and prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e){System.out.println(e);}
} }
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String[] args)
{
try {
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e){System.out.println(e);}
} }
Output: To execute this program open two command prompts and execute each program at each command
prompt as displayed in the below figure. After running the client application, a message will be displayed on the
server console.
Example of Java Socket Programming (Read-Write both side): In this example, client will write first
to the server then server will receive and print the text. Then server will write to the client and client will receive
and print the text. The step goes on. (TWO- WAY Communication)
Output:- To execute this program open two command prompts and execute each program at each command
prompt as displayed in the below figure. After running the client & Server applications, multiple message can be
send form both sides & will be displayed on the both (client –server) console. The communication will halt when
‘stop’ message sent.
Java & the Net:
The systems connected over a network through the Internet connect to each other with the help of
Transmission Control Protocol (TCP) or User Datagram Protocol (UDP). In Java, programming is done on
the application layer that uses the concept of classes in the java.net package; these classes provide a
system-independent network.
Consider an example of communication that occurs between two ends, such as a telephone conversation.
TCP ensures that the data send from one end to other goes in the same order as it was sent. Otherwise,
error occurs.
The examples of applications that need a consistent communication network are Hypertext Transfer
Protocol (HTTP), File Transfer Protocol (FTP), and Telnet. The success of these applications depends on the
sequence in which the data is set and received over the network. To read the data from the Uniform
Resource Locator (URL), the data must be received in the same order it was sent. Otherwise, a corrupt zip
file or an HTML file is retrieved in the end.
The UDP is connectionless unlike TCP. It sends datagrams (independent packets of data) from one
application to another. Here, there is no significance of the order of delivery and cannot be guaranteed
because each message is not related to the other & is used in multicasting.
Basically, a computer has a single physical connection with a network, and all the other devices are
associated with it through this network. The data transmitted over the network is identified by its address
that consists of IP address and port number.
Java supports TCP/IP both by extending the already established stream I/O interface and by adding the
features required to build I/O objects across the network. Java supports both the TCP and UDP protocol
families. TCP is used for reliable stream-based I/O across the network. UDP supports a simpler, hence
faster, point-to-point datagram-oriented model.
Java makes it easy to connect to other computers in Network using the classes contained in the java.net
package as shown:
Description of java.net Classes:
InetAddress
The platform on which TCP and UDP are built is called Internet Protocol (IP) address. An IP address
comprises either a 32-bit or 128-bit unsigned number used by IP and uses host name with which either it
may be constructed or have done a reverse host name resolution. An IP address specifies a number used
for identifying a particular host computer on the Internet.
The InetAddress class is used to encapsulate both the numerical IP address and the domain name
for that address. You interact with this class by using the name of an IP host, which is more convenient and
understandable than its IP address. The InetAddress class hides the number inside. InetAddress can handle
both IPv4 and IPv6 addresses.
java.net.Inet :- The java.net.Inet Address class is the lowest-level Java API for working with IP addresses.
Instances of InetAddress represent individual addresses and the InetAddress class provides the API for
using the platform’s name service to map a string hostname to a numeric IP address.
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:
The following example prints the addresses and names of the local machine and two Internet web sites as Output:
Socket defines several instance methods. For example, a Socket can be examined at any time for the
address and port information associated with it, by use of the following methods:
We can gain access to the input and output streams associated with a Socket by use of methods:
Whois: WHOIS (pronounced "who is") is an Internet service used to look up information about a
domain name. While the term is capitalized, "WHOIS" is not an acronym. Instead, it is short for the
question, "Who is responsible for this domain name?" Domain names are registered through
companies called registrars. “Internic.net” is the InterNIC web site that handles whois requests & sends
information about the website that was passes as a string in request.
The following program provides a simple Socket example. It opens a connection to a “whois”
port (port 43) on the InterNIC server, sends the command-line argument down the socket, and then
prints the data that is returned. InterNIC will try to look up the argument (website) as a registered
Internet domain name, and then send back the IP address and contact information for that site.
class Whois
{
public static void main(String args[]) throws Exception
{
int c;
// Create a socket connected to internic.net, port 43.
Socket s = new Socket("internic.net", 43);
// Obtain input and output streams.
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// Construct a request string.
String str = (args.length == 0 ? "osborne.com" : args[0]) + "\n";
// Convert to bytes.
byte buf[] = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((c = in.read()) != -1)
{
System.out.print((char) c);
}
s.close();
}
}
Output: (IP address and contact information of that site passed as argument)
Whois Server Version 1.3
Domain names in the .com, .net, and .org domains can now be registered with many different competing
registrars. Go to http://www.internic.net for detailed information.
Domain Name: OSBORNE.COM
Registrar: NETWORK SOLUTIONS, INC.
Whois Server: whois.networksolutions.com
Referral URL: http://www.networksolutions.com
Name Server: NS1.EPPG.COM
Name Server: NS2.EPPG.COM
..
..
..
URL: URL stands for Uniform Resource Locator also known as an internet address or web address.
A URL is nothing more than the address of a given unique resource on the Web. In theory, each
valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image,
etc.
An example of a URL is https://www.google.com, which is the URL for the Google Website.
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. Within
Java’s network class library, the URL class provides a simple, concise API to access information across
the Internet using URLs. URLs share the same basic format, although some variation is allowed.
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.
//Program to create a URL to Google download page and then examines its properties:
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()); // prints protocol of URL Passed
System.out.println("Port: " + hp.getPort()); // prints port Number of URL Passed
System.out.println("Host: " + hp.getHost()); // prints Host Name of URL Passed
System.out.println("File: " + hp.getFile()); // prints File Name of URL Passed
System.out.println("Ext:" + hp.toExternalForm());
}
}
Output:
Note: port is –1; this means that a port was not explicitly set.
URI class: URI class, which encapsulates a Uniform Resource Identifier (URI). URI’s are similar to URLs. In
fact, URLs constitute a subset of URIs. “A URI represents a standard way to identify a resource & a compact
sequence of characters that identifies an abstract or physical resource.”
“A URI can be further classified as a locator, a name, or both. A URL also describes how to access
the resource”. URL is a URI, abstractly speaking, but not every URI is a URL. This is because there is
another subcategory of URIs, uniform resource names (URNs), which name resources but do not specify
how to locate them. The difference between an object of URI class and an URL class lies in the fact that a
URI string is parsed only with consideration of syntax and no lookups of host is performed on creation.
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. These attributes are exposed by the
HTTP protocol specification and, as such, only make sense for URL objects that are using the HTTP
protocol. URLConnection defines several methods. Here is a sampling:
The following example creates a URLConnection using the openConnection( ) method of a URL object
and then uses it to examine the document’s properties and content:
// Demonstrate URLConnection.
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();
// get date
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
// get content type
System.out.println("Content-Type: " + hpCon.getContentType());
// get expiration date
d = hpCon.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
// get last-modified date
d = hpCon.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
// get content length
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(); //get document content
int i = len;
while (((c = input.read()) != -1)) { // && (--i > 0)) {
System.out.print((char) c);
}
input.close();
}
else {
System.out.println("No content available.");
}}}
Output: The program establishes an HTTP connection to www.internic.net over port 80. It then displays several header values and
retrieves the content. Here are the first lines of the output (the precise output will vary over time).
Date: Thu Feb 25 22:30:07 IST 2021
Content-Type: text/html; charset=UTF-8
Expires: Thu Mar 25 22:30:07 IST 2021
Last-Modified: Sun Jun 11 05:31:00 IST 2017
Content-Length: 8884
=== Content ===
<!DOCTYPE html>
<html>
<head>
<title>InterNIC | The Internet's Network Information Center</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Public Information Regarding Internet Domain Name Registration Services.">
<link href="https://www.internic.net/stylesheet/c670aa6c0c50da580c04a05784c3c62fbd834bd3.css" rel="stylesheet">..............
TCP/IP Server Sockets :
As mentioned earlier, Java has a different socket class that must be used for creating server
applications. The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports. ServerSockets are quite different from normal
Sockets. 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. The constructors might throw an IOException under adverse conditions.
Here are three of its constructors:
ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to
initiate communications and then return with a normal Socket that is then used for communication
with the client.
Here’s an Example. We’ll set up a client program that connects to a server program, sends a message,
and gets a message back. In this case, we’ll use the DNS 127.0.0.1 (the localhost), which means that
both the server and the client will be on the same machine.
//Java Program to create client application, which sends the message “Hello!” to the server and reads
what the server sends back:
import java.net.*;
import java.io.*;
class TCPClientCode
{
public static void main(String args[]) throws Exception
{
int character;
Socket socket = new Socket("127.0.0.1", 8765);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
String string = "Hello!!\n";
byte buffer[] = string.getBytes();
out.write(buffer);
while ((character = in.read()) != -1)
{
System.out.print((char) character);
}
socket.close();
}
}
Here’s the server application, which reads the message from the client and returns it, after prefacing it
with the text “The server got this”:
import java.io.*;
import java.net.*;
public class TCPServerCode
{
public static void main(String[] args )
{
try
{
ServerSocket socket = new ServerSocket(8765);
Socket insocket = socket.accept( );
BufferedReader in = new BufferedReader
(new InputStreamReader(insocket.getInputStream()));
PrintWriter out =
new PrintWriter(insocket.getOutputStream(), true);
String instring = in.readLine();
out.println("The server got this: " + instring);
insocket.close();
}
catch (Exception e) { }
}
}
Output: To run these applications, you’ll need two console windows (for example, in Windows, open two DOS
windows). Run the server first in one window as shown in RIGHT Figure and then the client in the other. When you do,
the client reports as shown in LEFT Figure.
Java has a different Socket class that must be used for creating server applications. You can use the
ServerSocket class for building servers that listen either for local or remote client programs for
connecting them on published ports as done in above program. Since the Web are driving most of the
activities on the internet, we here develop an operational Web (http) server. If you are programming a
server, then this is how you open a socket:
ServerSocket MyService;
try { MyService = new ServerSocket(PortNumber); }
catch (IOException e) { System.out.println(e); }
A Socket object must be created from the ServerSocket class for the implementation of the server to
listen for connections and accept them from clients:
Socket clientSocket = null;
try { serviceSocket = MyService.accept(); }
catch (IOException e) { System.out.println(e); }
Datagram: Datagrams are bundles of information passed between machines. They are somewhat
like a hard throw from a well-trained but blindfolded catcher to the third baseman. Once the
datagram has been released to its intended target, there is no assurance that it will arrive or even
that someone will be there to catch it. Likewise, when the datagram is received, there is no
assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a
response.
Datagram
Sender Receiver
Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket
object is the data container, while the DatagramSocket is the mechanism used to send or receive the
DatagramPackets. Each is examined here.
DatagramSocket: DatagramSocket defines four public constructors. They are shown here:
SN Constructors Description
1. DatagramSocket( ) Creates a DatagramSocket bound to any
throws SocketException unused port on the local computer
2. DatagramSocket(int port) Creates a DatagramSocket bound to the port
throws SocketException specified by port
3. DatagramSocket(int port,InetAddress ipAddress) Constructs a DatagramSocket bound to the
throws SocketException specified port and InetAddress
4. DatagramSocket(SocketAddress address) Constructs a DatagramSocket bound to the
throws SocketException specified SocketAddress
SN Methods Dercription
1. send( ) sends packet to the port specified by packet
2. receive( ), receive method waits for a packet to be received from the
port specified by packet and returns the result
3. InetAddress getInetAddress( ) If the socket is connected, then the address is returned.
Otherwise, null is returned.
4. int getLocalPort( ) Returns the number of the local port.
5. int getPort( ) Returns the number of the port to which the socket is
connected.Returns –1 if socket is not connected to a port.
6. boolean isBound( ) Returns true if the socket is bound to an address. Returns
false otherwise.
7. boolean isConnected( ) Returns true if the socket is connected to a server. Returns
false otherwise.
DatagramPacket: DatagramPacket defines several constructors. Four are shown here:
SN Constructors Description
1. DatagramPacket (byte data[ ], int size) specifies a buffer that will receive data and
the size of a packet
2. DatagramPacket (byte data[ ], int offset, int size) allows to specify an offset into the buffer at
which data will be stored
3. DatagramPacket (byte data[ ], int size, specifies a target address and port, which are
InetAddress ipAddress, int port) used by a DatagramSocket to determine
where the data in the packet will be sent
4. DatagramPacket(byte data[ ], int offset, int size, used to transmits packets beginning at the
InetAddress ipAddress, int port) specified offset into the data.
DatagramPacket defines several methods, including those shown here, that give access to the
address and port number of a packet, as well as the raw data and its length. In general, the get methods
are used on packets that are received and the set methods are used on packets that will be sent.
Datagram Definition: DataPacket sent over the network using UDP is organized in the form of
Datagram. A datagram consist of 4 Fields (each of 2 bytes) contains header information & remaining
part contains message/data. UDP Header information consists:
1. Source Port Number
2. Destination Port Number
3. Datagram Size
4. Checksum(error checking)
Datagram Server & Client Example: The following example implements a very simple
networked communications client and server. Messages are typed into the window at the server
and written across the network to the client side, where they are displayed.
// Creating UDP client application, which accepts the messages send from the server and displays it:
import java.net.*;
class UDPClientApp
{
public static int servPort = 997;
public static int clntPort = 998;
public static int buff_size = 1024;
public static DatagramSocket ds;
public static byte buff[] = new byte[buff_size];
public static void client() throws Exception
{
while(true)
{
DatagramPacket p = new DatagramPacket(buff, buff.length);
ds.receive (p);
System.out.println (new String (p.getData(), 0,
p.getLength())); }
}
public static void main (String args[]) throws Exception
{
ds = new DatagramSocket (clntPort);
client();
}
}
// Creating UDP Server application, which sends the messages to client without acknowledgement:
import java.net.*;
class UDPServerApp
{
public static int servPort = 997;
public static int clntPort = 998;
public static int buff_size = 1024;
public static DatagramSocket ds;
public static byte buff[] = new byte[buff_size];
public static void Server() throws Exception
{
int pos =0;
while (true)
{
int c = System.in.read();
switch (c)
{
case -1:
System.out.println ("Server Quits");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket
(buff,pos,InetAddress. getLocalHost(),clntPort));
pos = 0;
break;
default:
buff[pos++] = (byte) c; }
}
}
public static void main (String args[]) throws Exception
{
ds = new DatagramSocket (servPort);
Server();
}
}
Output: To run these applications, you’ll need two console windows (for example, in Windows, open two DOS windows).
Run the server first in one window as shown in RIGHT Figure and then the client in the other. When a message is sent from
server to client, the client if receive & accepts displays output message as shown in LEFT Figure