The following program demonstrates How to Create an Echo Server in Java.
Problem Statement
Write a TCP/IP client-server program that echoes whatever is typed on the client to the server.
Solution
The following code shows a simple Java TCP/IP client-server program where the server echoes whatever is typed by the client.
Server
import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) {
final int PORT = 12345;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
while (true) {
try (Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
System.out.println("Client connected: " + clientSocket.getInetAddress());
String message;
while ((message = in.readLine()) != null) {
System.out.println("Received: " + message);
out.println("Server Echo: " + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) {
final String SERVER_IP = "127.0.0.1"; // Change this to the server's IP address
final int SERVER_PORT = 12345;
try (Socket socket = new Socket(SERVER_IP, SERVER_PORT);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
System.out.println("Connected to the server at " + SERVER_IP + ":" + SERVER_PORT);
System.out.println("Type 'exit' to quit.");
String userInputLine;
while ((userInputLine = userInput.readLine()) != null) {
out.println(userInputLine);
if (userInputLine.equalsIgnoreCase("exit")) {
System.out.println("Client exiting.");
break;
}
String serverResponse = in.readLine();
System.out.println("Server Response: " + serverResponse);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note:
- Replace
"127.0.0.1"
in theSERVER_IP
variable in the client code with the actual IP address or hostname of your server. - The server listens on port
12345
in this example, but you can change it to any available port. - The client sends user input to the server, and the server echoes the input back to the client. The client can exit by typing “exit”.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go