Network Programming
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, the scenario is known as
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 Protocols
As 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:
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.
2. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a
connection-less protocol that allows data packets to be transmitted between different
applications. UDP is a simpler Internet protocol in which error-checking and
recovery services are not required. In UDP, there is no overhead for opening a
connection, maintaining a connection, or terminating a connection. In UDP, the data
is continuously sent to the recipient, whether they receive it or not.
Java Networking Terminology
In Java Networking, many terminologies are used frequently. These widely used
Java Networking Terminologies are given as follows:
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.
Range of the IP Address – 0.0.0.0 to 255.255.255.255
For Example – 192.168.0.1
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.
Protocol
A protocol is a set of rules basically that is followed for communication. For
example:
TCP
FTP
Telnet
25SMTP
POP etc.
MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with unique
MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
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)
Socket Programming
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 2627 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 Class
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
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.
Method Description
public void connect(SocketAddress This method is used to connect the
host, int timeout) socket to the particularized host. This
method is required only when the user
instantiates the Socket applying the
no-argument constructor.
public int getPort() This method is used to return the port
to which the socket is pined on the
remote machine.
public InetAddress This method is used to return the
getInetAddress() location of the other computer to
which the socket is connected.
public int getLocalPort() This method is used to return the port
to which the socket is joined on the
local machine.
public SocketAddress This method returns the location of the
getRemoteSocketAddress() remote socket.
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
The 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
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.
public void setSoTimeout(int This method is used to set time-out
timeout) value for the time in which the server
socket pauses for a client during the
accept() method.
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 time times
out, considering that the timeout value
has been set using the setSoTimeout()
method. Otherwise, this method will
be blocked indefinitely.
public void bind(SocketAddress This method is used to bind the socket
host, int backlog) 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.
import java.io.*;
import java.net.*;
public class SocketClient {
private Socket socket;
private DataInputStream consoleInput; // from keyboard
private DataOutputStream out; // to server
private DataInputStream in; // from server
public SocketClient(String address, int port) {
try {
socket = new Socket(address, port);
System.out.println("Connected to server");
consoleInput = new DataInputStream(System.in);
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
String line = "";
while (!line.equals("End")) {
// send message to server
System.out.print("You: ");
line = consoleInput.readLine();
out.writeUTF(line);
if (line.equals("End")) break;
// wait for server reply
String response = in.readUTF();
System.out.println("Server: " + response);
}
// close resources
consoleInput.close();
out.close();
in.close();
socket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
new SocketClient("127.0.0.1", 5000);
}
}
import java.io.*;
import java.net.*;
public class SocketServer {
private Socket socket;
private ServerSocket server;
private DataInputStream in; // from client
private DataOutputStream out; // to client
private DataInputStream consoleIn; // from server keyboard
public SocketServer(int port) {
try {
server = new ServerSocket(port);
System.out.println("Server started. Waiting for client...");
socket = server.accept();
System.out.println("Client connected");
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
consoleIn = new DataInputStream(System.in);
String line = "";
while (!line.equals("End")) {
// wait for client message
line = in.readUTF();
System.out.println("Client: " + line);
if (line.equals("End")) break;
// send reply to client
System.out.print("Server: ");
String response = consoleIn.readLine();
out.writeUTF(response);
}
// close resources
in.close();
out.close();
consoleIn.close();
socket.close();
server.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
new SocketServer(5000);
}
}
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.
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);
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( "smtp.gmail.com");
System.out.println("Inet Address of named hosts : " + address1);
// To get and print ALL InetAddress of Named Host
InetAddress arr[] = InetAddress.getAllByName( "www.gmail.com");
System.out.println("\nInet Address of ALL named hosts :");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
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);