Advanced Java ProgrammingUnit 79 min read
Java Networking & Socket Programming: UDP/TCP, RMI, CORBA, and Multiclient Architectures
Unit 7 of Advanced Java Programming covers Java’s networking capabilities, including UDP/TCP socket programming, client-server architectures, Remote Method Invocation (RMI), and CORBA, with hands-on examples, protocol comparisons, and real-world applications like chat systems and distributed computing.
TAKEAWAYS:
- Socket programming enables bidirectional communication between clients and servers using TCP (reliable, connection-oriented) or UDP (fast, connectionless) protocols.
- RMI allows Java objects to invoke methods remotely across networks, abstracting low-level socket details with stub/skeleton architecture.
- CORBA extends RMI’s functionality to heterogeneous systems (Java, C++, Python) via IDL (Interface Definition Language) and IIOP (Internet Inter-ORB Protocol).
- Multiclient-server models (e.g., UDP broadcast, TCP multiplexing) require thread-safe design to handle concurrent client requests efficiently.
- Networking APIs like
java.netandjavax.rmiprovide classes for sockets, datagrams, and remote object binding, with security considerations for firewalls and serialization. - Exam focus: Code implementation (e.g., UDP echo server, RMI calculator), protocol comparisons, and troubleshooting (e.g., port conflicts, serialization errors).
1. Java Networking Fundamentals
Java’s networking is built on TCP/IP and UDP/IP protocols, accessible via the java.net package. Key classes:
Socket/ServerSocket: TCP-based communication (stream-oriented, reliable).DatagramSocket/DatagramPacket: UDP-based communication (datagram-oriented, fast but unreliable).InetAddress: Resolves hostnames (e.g.,"google.com") to IP addresses.
TCP vs. UDP: A Comparison
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Guaranteed delivery | No guarantee |
| Speed | Slower (handshakes) | Faster (no overhead) |
| Use Cases | File transfer, HTTP, RMI | Video streaming, DNS, chat |
| Flow Control | Yes (sliding window) | No |
| Error Handling | Retransmits lost packets | Drops lost packets |
Example: UDP Echo Server/Client
// UDP Server (receives and echoes back)
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + received);
serverSocket.send(packet); // Echo back
serverSocket.close();
// UDP Client (sends "Hello" to server)
DatagramSocket clientSocket = new DatagramSocket();
String message = "Hello";
byte[] sendBuffer = message.getBytes();
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, serverAddress, 9876);
clientSocket.send(sendPacket);
clientSocket.close();
2. Socket Programming: Client-Server Architecture
TCP Socket Example: Chat Application
// Server (handles multiple clients using threads)
ServerSocket server = new ServerSocket(12345);
while (true) {
Socket clientSocket = server.accept();
new Thread(new ClientHandler(clientSocket)).start();
}
class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket socket) { this.clientSocket = socket; }
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client says: " + inputLine);
}
clientSocket.close();
}
}
// Client (sends messages to server)
Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello from client!");
socket.close();
Key Concepts:
ServerSocket.accept(): Blocks until a client connects.- Threading: Each client runs in a separate thread to handle concurrent requests.
- Streams:
InputStream/OutputStreamfor byte-level I/O;BufferedReader/PrintWriterfor text.
3. Remote Method Invocation (RMI)
RMI enables remote object invocation transparently, hiding network details. Architecture:
flowchart TD
A[Client] -->|Method Call| B[Stub]
B -->|Marshals Args| C[Network]
C --> D[Skeleton]
D --> E[Remote Object]
E -->|Returns| D
D -->|Unmarshals Result| C
C --> B
B --> ASteps to Implement RMI:
- Define Remote Interface: Extend
java.rmi.Remote.public interface Calculator extends Remote { int add(int a, int b) throws RemoteException; } - Implement Remote Object:
public class CalculatorImpl extends UnicastRemoteObject implements Calculator { public CalculatorImpl() throws RemoteException {} public int add(int a, int b) { return a + b; } } - Register Remote Object:
Calculator calc = new CalculatorImpl(); Naming.rebind("rmi://localhost/calc", calc); - Client Invocation:
Calculator stub = (Calculator) Naming.lookup("rmi://localhost/calc"); int result = stub.add(5, 3); // Remote call!
Advantages:
- Transparency: Objects appear local.
- Language Independence: Java-only (unlike CORBA).
- Security: Built-in authentication via
RMISecurityManager.
Disadvantages:
- Complexity: Requires stub/skeleton generation (use
rmictool or annotations). - Performance Overhead: Serialization/marshalling of objects.
4. Common Object Request Broker Architecture (CORBA)
CORBA extends RMI to heterogeneous systems (Java, C++, Python) using:
- IDL (Interface Definition Language): Defines interfaces independently of implementation.
- ORB (Object Request Broker): Middleware that routes requests (e.g.,
omniORB,JacORB). - IIOP (Internet Inter-ORB Protocol): Standard protocol for inter-ORB communication.
Example IDL:
interface Calculator {
long add(in long a, in long b);
};
Advantages Over RMI:
- Cross-language support: C++/Python clients can call Java servers.
- Standardized: OMG (Object Management Group) specification.
Disadvantages:
- Complex Setup: Requires IDL compiler (
idlj) and ORB configuration. - Slower: Higher overhead than RMI for Java-to-Java calls.
5. Multiclient-Server Design
UDP Broadcast Example (Server Echoes to All Clients)
// Server broadcasts received messages to all clients
DatagramSocket serverSocket = new DatagramSocket(9876);
Map<InetAddress, DatagramSocket> clients = new HashMap<>();
while (true) {
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
serverSocket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Broadcasting: " + message);
// Send to all registered clients
for (DatagramSocket clientSocket : clients.values()) {
clientSocket.send(packet);
}
}
Thread-Safe TCP Multiplexer:
// Server handles multiple clients in separate threads
ExecutorService threadPool = Executors.newFixedThreadPool(10);
while (true) {
Socket client = serverSocket.accept();
threadPool.execute(new ClientHandler(client));
}
Key Challenges:
- Thread Safety: Use
synchronizedblocks orExecutorService. - Resource Leaks: Close sockets/streams in
finally. - Scalability: For >1000 clients, use non-blocking I/O (
NIO) or frameworks like Netty.
6. Common Pitfalls and Best Practices
| Issue | Solution |
|---|---|
| Port Already in Use | Use serverSocket.setReuseAddress(true). |
| Serialization Errors | Ensure all remote objects implement Serializable. |
| Firewall Blocking | Use localhost for testing; configure ports in production. |
| Deadlocks | Avoid nested accept()/send() calls. |
| Memory Leaks | Close sockets/streams in finally. |
Debugging Tips:
- Use
netstat -ano(Windows) orlsof -i :port(Linux) to check port usage. - Enable RMI logging:
-Djava.rmi.server.logCalls=true.
7. Exam Tip: What to Focus On
Code Implementation:
- Write UDP echo server/client or TCP chat from scratch.
- Implement RMI calculator with remote interface and client/server.
- Use threading for multiclient servers (e.g.,
ExecutorService).
Conceptual Questions:
- TCP vs. UDP: When to use each (e.g., UDP for DNS, TCP for HTTP).
- RMI Architecture: Stub/skeleton,
Naming.rebind(),RemoteException. - CORBA vs. RMI: Cross-language support, IDL, ORB.
- Multiclient Design: Thread pools, broadcast vs. unicast.
Troubleshooting:
- "Why does my RMI client fail?" → Check
RMISecurityManager, registry (rmiregistry), and serialization. - "UDP packets are lost." → UDP is unreliable; use retries or switch to TCP.
- "Why does my RMI client fail?" → Check
Short-Answer Tricks:
- Socket Lifecycle:
ServerSocket→accept()→Socket→close(). - RMI Steps: Interface → Implementation → Registry → Client Lookup.
- UDP vs. TCP: "TCP is like a phone call; UDP is like shouting."
- Socket Lifecycle:
Based on the TU BSc CSIT syllabus for Advanced Java Programming (CSC409), unit 7.
Discussion
Loading…