When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is known as networking.
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.
Networking supplements a lot of power to simple programs. With networks, a single program can regain information stored in millions of computers positioned anywhere in the world. Java is the leading programming language composed from scratch with networking in mind. Java Networking is a notion of combining two or more computing devices together to share resources.
All the Java program communications over the network are done at the application layer. The java.net package of the J2SE APIs comprises various classes and interfaces that execute the low-level communication features, enabling the user to formulate programs that focus on resolving the problem.
Common Network ProtocolsAs stated earlier, the java.net package of the Java programming language includes various classes and interfaces that provide an easy-to-use means to access network resources. Other than classes and interfaces, the java.net package also provides support for the two well-known network protocols. These are:
Note: You can study more about TCP and UDP from the Differences between TCP and UDP.
In Java Networking, many terminologies are used frequently. These widely used Java Networking Terminologies are given as follows:
The java.net package of the Java programming language includes various classes that provide an easy-to-use means to access network resources. The classes covered in the java.net package are given as follows -
The java.net package of the Java programming language includes various interfaces also that provide an easy-to-use means to access network resources. The interfaces included in the java.net package are as follows:
Java Socket programming is practiced for communication between the applications working on different JRE. Sockets implement the communication tool between two computers using TCP. Java Socket programming can either be connection-oriented or connection-less. In Socket Programming, Socket and ServerSocket classes are managed for connection-oriented socket programming. However, DatagramSocket and DatagramPacket classes are utilized for connection-less 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.
Steps to establishing a TCP connection between two computing devices using Socket Programming
The following are the steps that occur on establishing a TCP connection between two computers using socket programming are given as follows:
Step 1 - The server instantiates a ServerSocket object, indicating at which port number communication will occur.
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 ClassThe 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 created using java.net.Socket class has been correlated specifically with 1 remote host. If a user wants to connect to another host, then he must build a new socket object.
Methods of Socket Class
In Socket programming, both the client and the server have a Socket object, so all the methods under the Socket class can be invoked by both the client and the server. There are many methods in the 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 ClassThe ServerSocket class is used for providing 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.
Methods of ServerSocket Class:
There are many methods in the ServerSocket class which are very useful for the users. These methods are:
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:The below example illustrates a pretty basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection.
Client-Side Java Implementation:
Java
// A Java program for a ClientSide
import java.io.*;
import java.net.*;
public class clientSide {
// initialize socket and input output streams
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 socket
in = 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
Open two windows one for Server and another for Client.
1. First run the Server application. It will show -
Server started Waiting for a client …
2. Then run the Client application on another terminal. It will show:
Connected
and the server accepts the client and shows,
Client accepted
3. Then you can start typing messages in the Client window. Here is the sample video of the output.
InetAddressThe 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:
Methods of InetAddress Class
Java InetAddress class represents an IP address. The following given are the important methods of the 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:The Java implementation of the Inet Address class to illustrate the usage of methods is shown below:
Example 1:
Java
import java.net.*;
public class InetAddressExample1 {
public static void main(String[] args) throws UnknownHostException{
// To get and print InetAddress of the Local Host
InetAddress address = InetAddress.getLocalHost();
System.out.println("InetAddress of the Local Host : "+address);
// To get and print host name of the Local Host
String hostName=address.getHostName();
System.out.println("\nHost name of the Local Host : "+hostName);
}
}
InetAddress of the Local Host : localhost/127.0.0.1 Host name of the Local Host : localhost
Example 2:
Java
import java.net.*;
public class InetAddressExample2 {
public static void main(String[] args)
throws UnknownHostException
{
// To get and print InetAddress of Named Hosts
InetAddress address1 = InetAddress.getByName(
"write.geeksforgeeks.org");
System.out.println("Inet Address of named hosts : "
+ address1);
// To get and print ALL InetAddress of Named Host
InetAddress arr[] = InetAddress.getAllByName(
"www.geeksforgeeks.org");
System.out.println("\nInet Address of ALL named hosts :");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Output
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. URL is a string of text that recognizes all the sources on the Internet, showing us the address of the source, how to interact with it, and recover something from it.
Components of a URL
A URL can have many forms. The most general however follows a three-components system-
There are many methods in Java URL Class that are commonly used in Java Networking. These methods are:
S. No. Methods 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 MethodsThe Java implementation of the URL class to illustrate the usage of methods is shown below
Example 1:
Java
import java.net.*;
public class URLclassExample1 {
public static void main(String[] args)
throws MalformedURLException
{
// creates a URL with string representation.
URL url = new URL(
"https://write.geeksforgeeks.org/post/3038131");
// print the string representation of the URL
String s = url.toString();
System.out.println("URL :" + s);
}
}
URL :https://write.geeksforgeeks.org/post/3038131
Example 2:
Java
import java.net.*;
public class URLclassExample2 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
"https://write.geeksforgeeks.org/post/3038131");
// to get and print the protocol of the URL
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);
}
}
Protocol : https HostName : write.geeksforgeeks.org File Name : /post/3038131
Example 3:
Java
import java.net.*;
public class URLclassExample3 {
public static void main(String[] args)
throws MalformedURLException
{
URL url = new URL(
"https://write.geeksforgeeks.org/post/3038131");
// to get and print the default port of the URL
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);
}
}
Default Port : 443 Path : /post/3038131
This was a brief introduction to Java Networking. In this article, many important topics like Introduction of Java Networking, Common Network Protocols, Java Network Terminology, Java Networking Classes, Java Networking Interfaces, Socket Programming, Inet Address, and URL Class were covered.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4