Advanced Programming Chapter 5 Java Networking
Advanced Programming Chapter 5 Java Networking
In simple words, the term network programming is writing programs that can be executed over
various computing 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.
Java is the leading programming language composed from scratch with network programming.
Java Networking is a notion of combining two or more computing devices together to share
resources.
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
1. Sharing resources
2. Centralize software management
The java.net package of the Java programming language includes various classes that provide an
easy-to-use means to access network resources. For example Socket, ServerSocket,
DatagramSocket , DatagramPacket, InetAddress etc.
The java.net package also provides two well-known network protocols. These are
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
2) 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, Telnet, 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 Controller).
A network node can have multiple NIC but each with unique MAC address.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So, it is not reliable
but fast. The example of connection-less protocol is UDP.
6) 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.
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 following are the steps that occur on establishing a TCP connection between two computers
using socket programming:
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 the server.
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.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
To create the server application, we need to create the instance of ServerSocket class. Here, we are
using 5000 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 connect 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 example where client sends a text and server
receives and prints it. First create Java Project called Java_Networking_Project and create all the
classes discussed below under this project.
File: TCP_Client_Machine1.java
import java.io.*;
import java.net.*;
public class TCP_Client_Machine1 {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",5000);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
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.
File:TCP_Server_Machine2.java
import java.net.*;
import java.io.*;
class TCP_Server_Machine2{
public static void main(String args[])throws Exception{
try{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
import java.net.*;
import java.io.*;
class TCP_Client_Machine2{
public static void main(String args[])throws Exception{
try{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP (User Datagram Protocol) instead of TCP(Transmission Control
Protocol).
Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.
Java DatagramPacket is a message that can be sent or received. It is a data container. If you send
multiple packets, it may arrive in any order.
Datagrams are collection of information sent from one device to another device via the established
network. When the datagram is sent to the targeted device, there is no assurance that it will reach
to the target device safely and completely. The UDP protocol is used to implement the datagrams
in Java.
//UDP_Receiver.java
import java.net.*;
public class UDP_Receiver{
public static void main(String[] args) throws Exception {
try{ DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
Run UDP_Sender.java, run UDP_Receiver and again run UDP_Sender.java the message Welcome
java is displayed on UDP_Receiver console which is transferred from UDP_Sender
The java.net.InetAddress class provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com, etc.
An instance of InetAddress represents the IP address with its corresponding host name. An IP
address helps to identify a specific resource on the network using a numerical representation.
//InetAddressDemo.java
import java.io.*;
import java.net.*;
public class InetAddressDemo{
public static void main(String[] args){
try{
InetAddress ip1=InetAddress.getByName("www.javatpoint.com");
InetAddress ip2=InetAddress.getByName("www.google.com");
System.out.println("Javatpoint Host Name: "+ip1.getHostName());
System.out.println("Javatpoint IP Address: "+ip1.getHostAddress());
System.out.println("Google Host Name: "+ip2.getHostName());
System.out.println("Google IP Address: "+ip2.getHostAddress());
System.out.println("Your Machine Host Name, IP Address and MAC Address are : ");
String ipAddress_localmachine="", macAddress_localmachine="",hostname_localmachine="";
int i=0;
StringBuilder sb = new StringBuilder();
InetAddress inetAddress_localmachine =InetAddress.getLocalHost();
ipAddress_localmachine =inetAddress_localmachine.getHostAddress();
hostname_localmachine =inetAddress_localmachine.getHostName();
NetworkInterface network=NetworkInterface.getByInetAddress(inetAddress_localmachine);
byte[] hw=network.getHardwareAddress();
for(i=0; i<hw.length; i++)
sb.append(String.format("%02X%s", hw[i], (i < hw.length - 1) ? "-" :""));
macAddress_localmachine=sb.toString();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Connect your computer to internet and run the file and see the output. In my laptop I get the
information. When you run the file you may get the same Host Name and IP Address for
www.javatpoint.com and www.google.com because you may access the same server address of each
site, but you pc or laptop Machine Name, IP Address and MAC Address must be different from
the output shown below.