In Java networking, various methods are used to establish communication between two or more devices across a network. Here are the most common types:
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
// Server (run first)
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started, waiting for client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello from Server");
socket.close();
serverSocket.close();
}
}
// Client (run second)
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello Server");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverMessage = in.readLine();
System.out.println("Server says: " + serverMessage);
socket.close();
}
}
Output:
Server:
Server started, waiting for client...
Client connected
Client says: Hello Server
Client:
Server says: Hello from 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:
// Server (run first)
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("Server waiting for data...");
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received from client: " + message);
serverSocket.close();
}
}
// Client (run second)
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = "Hello UDP Server".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
clientSocket.close();
}
}
Output:
Server:
Server waiting for data...
Received from client: Hello UDP 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.io.*;
import java.net.*;
public class URLExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
Output:
(Displays the HTML content of the webpage: "https://www.example.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:
// Sender
import java.net.*;
public class MulticastSender {
public static void main(String[] args) throws Exception {
MulticastSocket socket = new MulticastSocket();
InetAddress group = InetAddress.getByName("230.0.0.1");
byte[] message = "Hello Multicast Group".getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length, group, 6789);
socket.send(packet);
socket.close();
}
}
// Receiver
import java.net.*;
public class MulticastReceiver {
public static void main(String[] args) throws Exception {
MulticastSocket socket = new MulticastSocket(6789);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);
byte[] buffer = new byte[1000];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + message);
socket.leaveGroup(group);
socket.close();
}
}
Output:
Receiver:
Received: Hello Multicast Group
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:
// Interface (shared by both client and server)
import java.rmi.*;
public interface MyRemote extends Remote {
String sayHello() throws RemoteException;
}
// Server
import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
public MyRemoteImpl() throws RemoteException {}
public String sayHello() {
return "Hello from Server";
}
public static void main(String[] args) {
try {
Naming.rebind("RemoteHello", new MyRemoteImpl());
System.out.println("Server ready");
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Client
import java.rmi.*;
public class MyRemoteClient {
public static void main(String[] args) {
try {
MyRemote service = (MyRemote) Naming.lookup("rmi://localhost/RemoteHello");
System.out.println(service.sayHello());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Server:
Server ready
Client:
Hello from Server
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.