In Java networking, various methods are used to establish communication between two or more devices across a network. Here are the most common types:
Contents
1.Socket Programming (TCP/IP)
Definition:
- Socket programming is based on the TCP/IP protocol, which provides reliable, connection-oriented communication between a client and a server. The server listens for incoming connections, and the client initiates the connection.
Example
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) {
try {
// Create a server socket listening on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server started, waiting for client connection...");
// Accept client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");
// Create input and output streams
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true);
// Read and respond to client messages
String message = input.readLine();
System.out.println("Client says: " + message);
output.println("Server received: " + message);
// Close resources
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Â
Output:
Server started, waiting for client connection...
Client connected!
Client says: Hello Server!
Advantages:
- Provides reliable and ordered communication.
- Connection-oriented, meaning that both sides ensure data is received correctly.
Uses:
- Web servers and web browsers.
- Remote command execution.
- File transfer between client and server.
2.Datagram (UDP) Programming
Definition:
- Datagram programming uses the UDP (User Datagram Protocol), which is connectionless and does not guarantee the delivery or ordering of packets. It’s faster but less reliable than TCP.
Example:
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(12345);
byte[] receiveData = new byte[1024];
System.out.println("Server listening on port 12345...");
// Receive data from client
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received from client: " + message);
// Send response to client
String response = "Server received: " + message;
DatagramPacket sendPacket = new DatagramPacket(response.getBytes(), response.length(), receivePacket.getAddress(), receivePacket.getPort());
socket.send(sendPacket);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Â
Output:
Server listening on port 12345...
Received from client: Hello Server!
Advantages:
- Faster than TCP since it has no overhead for establishing connections.
- Suitable for time-sensitive applications.
Uses:
- Real-time gaming.
- Video streaming.
- Voice-over-IP (VoIP).
3.URL (Uniform Resource Locator)
Definition:
- A URL is used to identify resources on the internet. The URL class in Java provides methods to fetch data from web resources over HTTP or HTTPS.
Example:
import java.net.*;
import java.io.*;
public class URLExample {
public static void main(String[] args) {
try {
// Create URL object for the website
URL url = new URL("http://www.kaashiv.com");
// Open connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print the response content
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
The output will be the HTML content of the page at http://www.kaashiv.com.
Advantages:
- Easy to interact with web resources.
- Can handle different protocols like HTTP, HTTPS, and FTP.
Uses:
- Web scraping.
- Fetching content from APIs.
- Downloading files from the internet.
4.Multicast
Definition:
- Multicasting allows sending data to multiple recipients simultaneously using the UDP protocol. Java supports multicast communication using the MulticastSocket class.
Example:
import java.net.*;
public class MulticastExample {
public static void main(String[] args) {
try {
MulticastSocket socket = new MulticastSocket(12345);
InetAddress group = InetAddress.getByName("230.0.0.1"); // Multicast address
socket.joinGroup(group);
// Send message to multicast group
String message = "Hello, Multicast Group!";
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), group, 12345);
socket.send(packet);
// Receive message from multicast group
byte[] buffer = new byte[256];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + response);
socket.leaveGroup(group);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advantages:
- Efficient for sending data to multiple recipients without duplication.
- Reduces bandwidth usage for large-scale broadcasting.
Uses:
- Video conferencing.
- Live streaming.
- Distributed systems.
5.Remote Method Invocation (RMI)
Definition:
- Remote Method Invocation (RMI) enables a Java program to invoke methods of objects residing on different JVMs. It allows distributed applications to communicate and share resources across the network.
Example:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
// Create the Server Program
public class RMIServer {
public static void main(String[] args) {
try {
// Create an instance of the remote object
CalculatorImpl calc = new CalculatorImpl();
// Create RMI registry if it does not exist
LocateRegistry.createRegistry(1099);
// Bind the remote object to a name in the RMI registry
Naming.rebind("CalculatorService", calc);
System.out.println("Server is ready.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Server is ready.
Advantages:
- Allows seamless method calls over a network, making remote objects behave like local ones.
- Simplifies distributed application development.
Uses:
- Distributed applications.
- Remote database access.
- Enterprise-level applications.