//* Single Client Echo server in Java, echoing one line of text at a time *

import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.PrintWriter; import java.net.Socket; import java.net.ServerSocket; class Test { // what port people will be "knocking at"/ connecting to static final int port = 60000; // maximum # of connections waiting to be taken care of static final int maxque = 2; public static void main(String A[]) { try { ServerSocket SERV= new ServerSocket(port, maxque); System.out.println("Test server started at port "+port); while (true) // let us try to catch local errors inside this loop without quiting the server try { // wait for the next client connection Socket SO=SERV.accept(); System.out.println("A new client connected from "+SO.getInetAddress()); // create a stream for reading via socket connection BufferedReader SR=new BufferedReader(new InputStreamReader(SO.getInputStream())); // create a stream for writing via socket connection PrintWriter SW=new PrintWriter (SO.getOutputStream()); SW.println("I am listening to you."); SW.flush(); System.out.println("listening..."); while (true) { String line=SR.readLine(); if (line==null) break; System.out.println(line); } SO.close(); System.out.println("The client closed connection."); } catch (Exception e) { System.out.println("Ops! "+e); System.out.println("Returning to main server loop."); } } catch (Exception e) { System.out.println("Fatal Ops! "+e); } } }