To implement a simple TCP client and server in Java, you use the ServerSocket class for the server and the Socket class for the client.
Here is a straightforward example of both, where they exchange simple text messages.
1. The TCP Server
The server listens on a specific port and waits for a client to connect. Once connected, it opens input and output streams to communicate.
package org.kodejava.net;
import java.io.*;
import java.net.*;
public class SimpleTCPServer {
public static void main(String[] args) {
int port = 8080;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
// Wait for a client connection
try (Socket socket = serverSocket.accept()) {
System.out.println("Client connected!");
// Setup streams for communication
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// Read message from a client
String clientMessage = reader.readLine();
System.out.println("Received from client: " + clientMessage);
// Send a response back
writer.println("Hello from Server!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. The TCP Client
The client connects to the server’s IP address (or localhost) and the same port number.
package org.kodejava.net;
import java.io.*;
import java.net.*;
public class SimpleTCPClient {
public static void main(String[] args) {
String hostname = "localhost";
int port = 8080;
try (Socket socket = new Socket(hostname, port)) {
// Setup streams for communication
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Send a message to the server
writer.println("Hello from Client!");
// Read the server's response
String response = reader.readLine();
System.out.println("Server says: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
How to run it:
- Start the Server first: Run
SimpleTCPServer. It will sit and wait (“block”) at theaccept()method. - Start the Client: Run
SimpleTCPClient. It will connect, send the message, and then both programs will finish.
Key Concepts:
ServerSocket: Used by the server to “listen” for incoming connection requests.Socket: Represents the actual connection. Both the client and the server use aSocketobject to talk to each other once the connection is established.- Try-with-resources: Using
try (...)ensures that the sockets and streams are automatically closed, even if an error occurs. - Blocking: The
accept()andreadLine()methods are “blocking,” meaning the program pauses there until a connection is made or data is received.
