Java Networking and Design Patterns: Key Concepts
Posted on Mar 31, 2026 in Computers
Java Networking Classes Comparison
| Inet4Address | Inet6Address |
|---|
| Represents IPv4 address. | Represents IPv6 address. |
| 32-bit address. | 128-bit address. |
| Dotted decimal format (e.g., 192.168.1.1). | Hexadecimal colon format (e.g., 2001:db8::1). |
| Limited address space (about 4.3 billion). | Very large address space (2¹²⁸). |
| Simple header structure. | More advanced and larger header. |
Subclass of InetAddress for IPv4. | Subclass of InetAddress for IPv6. |
| URLConnection | HttpURLConnection |
|---|
| Superclass for all types of URL connections. | Subclass of URLConnection specifically for HTTP protocol. |
| Works with different protocols (HTTP, FTP, File, etc.). | Works only with HTTP and HTTPS protocols. |
| Cannot directly set HTTP request methods like GET or POST. | Can set request methods like GET, POST, PUT, DELETE using setRequestMethod(). |
Provides general methods like connect(), getInputStream(). | Provides HTTP-specific methods like getResponseCode(), getResponseMessage(). |
| Does not handle HTTP response codes directly. | Can access HTTP status codes (200, 404, etc.). |
| More generic and protocol-independent. | More specific and used for web communication. |
| Blocking Socket | Non-Blocking Socket |
|---|
| Execution waits until operation completes. | Execution does not wait; continues immediately. |
read() blocks until data is available. | read() returns immediately even if no data. |
Uses traditional java.net.Socket and ServerSocket. | Uses java.nio package (SocketChannel, ServerSocketChannel). |
| Simpler to implement. | More complex to implement. |
| One thread per connection is usually required. | One thread can handle multiple connections. |
| Slower for large-scale applications. | More efficient and scalable for many clients. |
| RMI (Remote Method Invocation) | Socket Programming |
|---|
| Used to invoke methods on remote objects. | Used to send and receive data between systems. |
| Works at application level (high-level API). | Works at transport level (low-level API). |
Uses Java RMI package (java.rmi). | Uses java.net package (Socket, ServerSocket). |
| Automatically handles object serialization. | Programmer must manually handle data transmission. |
| Easier to develop distributed applications in Java. | Requires more coding and protocol handling. |
| Only Java-to-Java communication. | Can communicate between different languages. |
| Built on top of sockets. | Basic communication mechanism. |
| TCP Socket | UDP Socket |
|---|
| Connection-oriented protocol. | Connectionless protocol. |
| Reliable data transfer. | Unreliable data transfer. |
| Ensures data delivery in correct order. | No guarantee of order or delivery. |
| Slower due to error checking and acknowledgment. | Faster due to less overhead. |
Uses Socket and ServerSocket classes in Java. | Uses DatagramSocket and DatagramPacket classes in Java. |
| Suitable for web, email, file transfer. | Suitable for live streaming, gaming, video calls. |
| URI Class | URL Class |
|---|
| Stands for Uniform Resource Identifier. | Stands for Uniform Resource Locator. |
| Identifies a resource by name or location. | Identifies the location of a resource on the web. |
| Can represent relative and absolute identifiers. | Always represents absolute address. |
| Does not provide methods to access resource content. | Can open connection to access resource (openConnection()). |
Part of java.net.URI. | Part of java.net.URL. |
| More general concept. | Subset of URI (specifically for locating resources). |
System Network Information
This program retrieves the IP and MAC addresses of the system and identifies the IP version (IPv4 or IPv6).
import java.net.*;
import java.util.Enumeration;
public class SystemNetworkInfo {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
while (networks.hasMoreElements()) {
NetworkInterface netInt = networks.nextElement();
if (!netInt.isUp() || netInt.isLoopback()) continue;
System.out.println("Interface Name: " + netInt.getName());
byte[] mac = netInt.getHardwareAddress();
if (mac != null) {
System.out.print("MAC Address: ");
for (int i = 0; i < mac.length; i++) {
System.out.printf("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
System.out.println();
}
Enumeration<InetAddress> addresses = netInt.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
System.out.println("IP Address: " + addr.getHostAddress());
if (addr instanceof Inet4Address) System.out.println("Type: IPv4");
else if (addr instanceof Inet6Address) System.out.println("Type: IPv6");
}
System.out.println("----------------------------");
}
} catch (Exception e) { e.printStackTrace(); }
}
}
Factory Method Pattern
The Factory Method pattern defines an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Example in Java
- Step 1: Product Interface
interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } }
class Rectangle implements Shape { public void draw() { System.out.println("Drawing Rectangle"); } }
- Step 3: Factory Class (Creator)
class ShapeFactory {
public Shape getShape(String type) {
if (type == null) return null;
if (type.equalsIgnoreCase("circle")) return new Circle();
else if (type.equalsIgnoreCase("rectangle")) return new Rectangle();
return null;
}
}
public class FactoryMethodExample {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape s1 = factory.getShape("circle"); s1.draw();
Shape s2 = factory.getShape("rectangle"); s2.draw();
}
}
Using DatagramChannel
DatagramChannel is a class in the java.nio.channels package used for UDP communication in Java NIO.
| Method | Description |
|---|
open() | Opens a datagram channel |
bind() | Binds channel to a port |
send() | Sends datagram |
receive() | Receives datagram |
connect() | Connects to remote address |
configureBlocking() | Sets blocking/non-blocking mode |
UDP Sender Example
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class DatagramSender {
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
String message = "Hello UDP";
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
InetSocketAddress address = new InetSocketAddress("localhost", 5000);
channel.send(buffer, address);
channel.close();
}
}
UDP Receiver Example
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class DatagramReceiver {
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
channel.bind(new InetSocketAddress(5000));
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.receive(buffer);
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println("Received: " + new String(data));
channel.close();
}
}
UDP Echo Client
import java.net.*;
public class UDPEchoClient {
public static void main(String args[]) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("localhost");
String msg = "Hello";
byte[] data = msg.getBytes();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, ip, 5000);
socket.send(sendPacket);
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server: " + response);
socket.close();
}
}