In simple words, the term network programming or networking associates with writing programs that can be executed over various computer devices, in which all the devices are connected to each other to share resources using a network. Here, we are going to discuss Java Networking.
- What is Java Networking?
- Common Network Protocols
- Java Network Terminology
- Java Networking Classes
- Java Networking Interfaces
- Socket Programming
- Inet Address
- URL Class
In simple words, the term network programming or networking associates with writing programs that can be executed over various computer devices, in which all the devices are connected to each other to share resources using a network. Here, we are going to discuss Java Networking.
- What is Java Networking?
- Common Network Protocols
- Java Network Terminology
- Java Networking Classes
- Java Networking Interfaces
- Socket Programming
- Inet Address
- URL Class
What is Java Networking?
Common Network Protocols
1. Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure communication between different applications. TCP is a connection-oriented protocol which means that once a connection is established, data can be transmitted in two directions. This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP. TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent, making it a complete protocol for transporting information like still images, data files, and web pages.
Java Networking Terminology
1. IP Address – An IP address is a unique address that distinguishes a device on the internet or a local network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the internet or local network. IP Address is referred to as a logical address that can be modified. It is composed of octets. The range of each octet varies from 0 to 255.
Range of the IP Address – 0.0.0.0 to 255.255.255.255
For Example – 192.168.0.1
2. Port Number – A port number is a method to recognize a particular process connecting internet or other network information when it reaches a server. The port number is used to identify different applications uniquely. The port number behaves as a communication endpoint among applications. The port number is correlated with the IP address for transmission and communication among two applications. There are 65,535 port numbers, but not all are used every day.
3. Protocol – A network protocol is an organized set of commands that define how data is transmitted between different devices in the same network. Network protocols are the reason through which a user can easily communicate with people all over the world and thus play a critical role in modern digital communications. For Example – TCP, FTP, POP, etc.
4. MAC Address – MAC address stands for Media Access Control address. It is a bizarre identifier that is allocated to a NIC (Network Interface Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network adapter. MAC address can be in hexadecimal composition. In simple words, a MAC address is a unique number that is used to track a device in a network.
5. Socket – A socket is one endpoint of a two-way communication connection between the two applications running on the network. The socket mechanism presents a method of inter-process communication (IPC) by setting named contact points between which the communication occurs. A socket is tied to a port number so that the TCP layer can recognize the application to which the data is intended to be sent.
Connection-oriented and connection-less protocol – In a connection-oriented service, the user must establish a connection before starting the communication. When the connection is established, the user can send the message or the information, and after this, they can release the connection. However, In connectionless protocol, the data is transported in one route from source to destination without verifying that the destination is still there or not or if it is ready to receive the message. Authentication is not needed in the connectionless protocol.
Example of Connection-oriented Protocol – Transmission Control Protocol (TCP)
Example of Connectionless Protocol – User Datagram Protocol (UDP)
CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache.
CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses.
CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy.
DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission by applying the datagram socket class.
InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses.
Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used.
Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object.
DatagramSocket – The DatagramSocket class is a network socket that provides a connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can further be practiced for transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism for providing network communication via UDP instead of TCP.
Proxy – A proxy is a changeless object and a kind of tool or method or program or system, which serves to preserve the data of its users and computers. It behaves like a wall between computers and internet users. A Proxy Object represents the Proxy settings to be applied with a connection.
URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to a database or a search engine.
URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection.
Java Networking Terminology
2. CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request.
Socket Programming
A client application generates a socket on its end of the communication and strives to combine that socket with a server. When the connection is established, the server generates an object of socket class on its communication end. The client and the server can now communicate by writing to and reading from the socket.
The java.net.Socket class describes a socket, and the java.net.ServerSocket class implements a tool for the server program to host clients and build connections with them.
The following are the steps that occur on establishing a TCP connection between two computers using socket programming are given as follows:
Step 2: After instantiating the ServerSocket object, the server requests the accept() method of the ServerSocket class. This program pauses until a client connects to the server on the given port.
Step 3: After the server is idling, a client instantiates an object of Socket class, defining the server name and the port number to connect to.
Step 4 – After the above step, the constructor of the Socket class strives to connect the client to the designated server and the port number. If communication is authenticated, the client forthwith has a Socket object proficient in interacting with the server.
Step 5 – On the server-side, the accept() method returns a reference to a new socket on the server connected to the client’s socket.
After the connections are stabilized, communication can happen using I/O streams. Each object of a socket class has both an OutputStream and an InputStream. The client’s OutputStream is correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol. Hence information can be transmitted over both streams at the corresponding time.
Socket Class
Methods of Socket Class
S No. | Method | Description |
---|---|---|
1 | public void connect(SocketAddress host, int timeout) | This method is used to connect the socket to the particularized host. This method is required only when the user instantiates the Socket applying the no-argument constructor. |
2 | public int getPort() | This method is used to return the port to which the socket is pinned on the remote machine. |
3 | public InetAddress getInetAddress() | This method is used to return the location of the other computer to which the socket is connected. |
4 | public int getLocalPort() | This method is used to return the port to which the socket is joined on the local machine. |
5 | public SocketAddress getRemoteSocketAddress() | This method returns the location of the remote socket. |
6 | public InputStream getInputStream() | This method is used to return the input stream of the socket. This input stream is combined with the output stream of the remote socket. |
7 | public OutputStream getOutputStream() | This method is used to return the output stream of the socket. The output stream is combined with the input stream of the remote socket. |
8 | public void close() | This method is used to close the socket, which causes the object of the Socket class to no longer be able to connect again to any server. |
ServerSocket Class
Methods of ServerSocket Class:
S No. | Method | Description |
---|---|---|
1 | public int getLocalPort() | This method is used to return the port that the server socket is monitoring on. This method is beneficial if a user passed 0 as the port number in a constructor and lets the server find a port for him. |
2 | public void setSoTimeout(int timeout) | This method is used to set the time-out value for the time in which the server socket pauses for a client during the accept() method. |
3 | public Socket accept() | This method waits for an incoming client. This method is blocked till either a client combines to the server on the specified port or the socket times out, considering that the time-out value has been set using the setSoTimeout() method. Otherwise, this method will be blocked indefinitely. |
4 | public void bind(SocketAddress host, int backlog) | This method is used to bind the socket to the particularized server and port in the object of SocketAddress. The user should use this method if he has instantiated the ServerSocket using the no-argument constructor. |
Example of Socket Programming in Java:
Client-Side Java Implementation:
// A Java program for a ClientSide
import java.io.*;
import java.net.*;
public class clientSide {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public clientSide(String address, int port)
{
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
}
catch (IOException i) {
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "End" is input
while (!line.equals("End")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}
// close the connection
try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String[] args)
{
clientSide client
= new clientSide("127.0.0.1", 5000);
}
}
Server Side Java Implementation:
// A Java program for a serverSide
import java.io.*;
import java.net.*;
public class serverSide {
// initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public serverSide(int port)
{
// starts server and waits for a connection
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println
("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socketin
= new DataInputStream(
new BufferedInputStream
(socket.getInputStream()));
String line = "";
// reads message from client until
"End" is sent
while (!line.equals("End")) {
try {
line = in.readUTF();
System.out.println(line);
}
catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String[] args)
{
serverSide server = new serverSide(5000);
}
}
To run on Terminal or Command Prompt
1. First run the Server application. It will show –
Server started
Waiting for a client …
Connected
Client accepted
3. Then you can start typing messages in the Client window. Here is the sample video of the output.
Connected
InetAddress
The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by 32-bit or 128-bit unsigned number. An object of InetAddress describes the IP address with its analogous hostname. InetAddress can control both IPv4 and IPv6 addresses.
There are two different types of addresses:
- Unicast – It is an identifier for a single interface.
- Multicast – It is an identifier for a collection of interfaces.
Methods of InetAddress Class
S No. | Method | Description |
---|---|---|
1 | static InetAddress getByAddress(byte[] addr) | This method is used to return an object of the InetAddress class provided the raw IP address. |
2 | static InetAddress getByAddress(String host, byte[] addr) | This method is used to create an InetAddress based on the given hostname and IP address. |
3 | static InetAddress getByName(String host) | This method is used to determine the IP address of a host when the host’s name is given. |
4 | static InetAddress InetAddress getLocalHost() | This method is used to return the localhost. |
5 | String getHostName() | This method is used to get the name of the IP address. |
6 | String getHostAddress() | This method returns the IP address in the form of a string in a textual display. |
7 | String toString() | This method is used to convert the IP address to a string. |
Examples of Inet Address Class Methods:
Examples
import java.net.*;
public class InetAddressExample1 {
public static void main(String[] args)
throws UnknownHostException{
InetAddress address =
InetAddress.getLocalHost();
System.out.println
("InetAddress of the Local Host : "+address);
String hostName=address.getHostName();
System.out.println
("\nHost name of the Local Host : "+hostName);
}
}
Output
InetAddress of the Local Host :
localhost/127.0.0.1
Host name of the Local Host : localhost
URL Class
Components of a URL
- Protocol – The protocol in a URL defines how information is transported among the host and a client (or web browser).
- Hostname – The hostname is the name of the device on which the resource exists.
- File Name – The filename is the pathname to the file on the device.
- Port Number – The port number is used to identify different applications uniquely. It is typically optional.
Methods of Java URL Class
There are many methods in Java URL Class that are commonly used in Java Networking. These methods are:-
S No. | Method | Description |
---|---|---|
1 | public String getProtocol() | This method returns the protocol that is used by the URL. |
2 | public String getHost() | This method returns the hostname of the URL in IPv6 composition. |
3 | public int getPort() | This method returns the port associated with the protocol specified by the URL. |
4 | public String getFile() | This method returns the filename. |
5 | public String getPath() | This method returns the path of the URL, or null if empty. |
6 | public String toString() | This method is used to return the string representation of the provided URL object. |
7 | public int getDefaultPort() | This method returns the default port used. |
Examples of URL Class Methods
Example 1:
import java.net.*;
public class URLclassExample1 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
"https://write javaprogramer/post/3038131");
String s = url.toString();
System.out.println("URL :" + s);
}
}
Example 2:
import java.net.*;
public class URLclassExample2 {
public static void mai(String[] args)
throws MalformedURLException
{
URL url = new URL(
"https://write javaprogramer/post/3038131");
String protocol = url.getProtocol();
System.out.println("Protocol
: " + protocol);
// to get and print
the hostName of the URL
String host = url.getHost();
System.out.println("HostName
: " + host);
// to get and print
the file name of the URL
String fileName = url.getFile();
System.out.println("File Name
: " + fileName);
}
}
Output
Protocol : https
HostName : write javaprogramer
File Name : /post/3038131
Example 3:
import java.net.*;
public class URLclassExample3 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
"https://write javaprogramer/post/3038131");
int defaultPort = url.getDefaultPort();
System.out.println("Default Port : "
+ defaultPort);
// to get and print the path of the URL
String path = url.getPath();
System.out.println("Path : " + path);
}
}
Output
Default Port : 443
Path : /post/3038131