Java EchoServer Example

I’m using this post to experiment with syntax highlighting in my blog.  Recently a friend needed a program to echo data on a socket while he was testing an internet appliance and some other network enabled hardware so I figured I’d just use that code as my example.

The EchoServer will open a listen socket on port 4444.  Compile it, run it and then to test it you can open a command prompt and type telnet localhost 4444

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
/**
 * @author NickC
 */
public class EchoServer {
   private static final int BUFFER_SIZE = 256; 
   private static int listenPort = 4444;
 
   public static void main(String[] args) throws Exception{
      ServerSocket serverSock = new ServerSocket(listenPort);
      System.out.println("listening on port "+listenPort);
      Socket sock = serverSock.accept();
      System.out.println("new connection " + sock);
 
      InputStream sockIn = sock.getInputStream();
      OutputStream sockOut = sock.getOutputStream();
      byte[] buffer = new byte[BUFFER_SIZE];
      while(true) {
         Thread.sleep(50);
         int count = 0;
         if ((count = sockIn.available()) > 0) {
            if (count >= buffer.length) {
               count = buffer.length;
            }
            count =  sockIn.read(buffer, 0, count);
            System.out.println("echoing "+count+" bytes");
            sockOut.write(buffer, 0, count);
            sockOut.flush();
         }
      }
   }
}

Source in a file: EchoServer.java


Leave a Reply