import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /* * Sample class to illustrate how to setup a server that listens * on a dedicated port for incoming TCP connections. */ public class MyServer { // port to bind to static int port = 1025; static boolean running = false; // standard program entry point public static void main(String args[]) { // The communication attempt must be embedded in a 'try-catch' block // to catch the many errors that could occur during communications try { // Starting server by binding to requested port if possible. ServerSocket server = new ServerSocket(port); System.out.println("Server started: " + server); // Setting up infinite loop to handle multiple client // connections in sequence. running = true; while (running) { // Waiting for incoming connection in a blocking call Socket socket = server.accept(); System.out.println("Connected: " + socket); // Now handling the client. It is embedded in its own // try-catch block to keep the server running even if // the client experiences an error (e.g. timeout). try { processClient(socket); } catch(IOException ioe) { System.err.println("Error: " + ioe.getMessage()); } // We are done so we close the client connection. The server // itself will remain running, waiting for the next client // to connect t the top of the loop. socket.close(); } // Closing down the server. At this time this statement is // unreachable (which should change in improved versions). server.close(); System.out.println("Server is now down"); } catch (IOException e) { // Printing error message for all IO exceptions e.printStackTrace(); } } private static void processClient(Socket socket) throws IOException { // Setup timeout (in milli-seconds) for blocking calls socket.setSoTimeout(10000); // Setting up IO stream to/from the connected client BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); PrintWriter out = new PrintWriter( new OutputStreamWriter( socket.getOutputStream())); System.out.println("IO setup complete."); // Now processing the data from the client String line = in.readLine(); if (line.equals("stopserver")) { running = false; } else { out.println("Bert's Echo: " + line); out.flush(); } // closing IO streams in.close(); out.close(); } }