Implementing an echo Server in Java

You can either use a TCP or UDP version. With UDP, you will have to use a DatagramSocket to create and listen to a port. With TCP (see example), you need to instantiate a ServerSocket. The echo port is 7. The server just creates a thread that loops indefinitely waiting for requests from clients and returns the exact same string the client contacted it with.

To test out following server, compile the source of EchoClient (see EchoClient) and run it using

java EchoClient localhost

EchoServer.java:

import java.util.*;
import java.net.*;
import java.io.*;
 
public class EchoServer {
   public static void main(String args[]) {
      EchoServerThread es = new EchoServerThread();
      es.start();
   }
}
 
class EchoServerThread extends Thread {
   private ServerSocket ss;
   private final int port = 7;
 
   public void run() {
      try {
         ss = new ServerSocket(port);
      } 
      catch(IOException e) {
         e.printStackTrace();
         return;
      }
 
      try { 
         while (true) {
            Socket clientSock = ss.accept();
            BufferedReader br = new BufferedReader(
                         new InputStreamReader(clientSock.getInputStream()));
            BufferedWriter bw = new BufferedWriter(
                         new OutputStreamWriter(clientSock.getOutputStream()));
  
            bw.write(br.readLine());
            clientSock.close();
         }
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}