Client-Server Communication using TCP/IP in Java
1. Introduction
TCP/IP (Transmission Control Protocol / Internet Protocol) is a reliable, connection-oriented protocol used for
communication between systems. In Java, TCP is implemented using the ServerSocket (for server) and
Socket (for client) classes.
2. Diagram
Diagram:
+------------+ TCP/IP +------------+
| Client | <-----------------------> | Server |
+------------+ (Socket) +------------+
| |
Socket class ServerSocket class
| |
Sends request -----------------> Accepts connection
Receives reply <---------------- Sends response
3. Server Code
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is running... Waiting for client.");
Socket socket = serverSocket.accept(); // Waits for client
System.out.println("Client connected.");
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
String clientMessage = input.readUTF();
System.out.println("Client says: " + clientMessage);
output.writeUTF("Hello from Server!");
Client-Server Communication using TCP/IP in Java
socket.close();
serverSocket.close();
}
}
4. Client Code
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000); // Connect to server
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
DataInputStream input = new DataInputStream(socket.getInputStream());
output.writeUTF("Hello from Client!");
String serverReply = input.readUTF();
System.out.println("Server says: " + serverReply);
socket.close();
}
}
5. Explanation and Conclusion
How it Works:
1. Server runs first and waits for a connection on port 5000.
2. Client connects to the server using the same port.
3. They exchange messages using input/output streams.
4. Communication is established using TCP, which guarantees delivery.
Conclusion:
Java uses Socket and ServerSocket for TCP communication. This allows real-time, reliable data exchange
between client and server systems.