1 package Networking;
 3 
 4 import java.io.*;
 5 import java.net.*;
 6 
 7 /**
 8  * The is an example of a simple server. NOTE: There is a particularly bad practice
 9  * implemented here where the client can tell the server to shut down! This is bad
10  * for (hopefully) obvious reasons, but is used here to keep the code simple...
11  * otherwise the server would have to be "interactive" and/or shutdown separately.
12  * @author aconover
13  */
14 public class Server {
15 
16     public static void main(String[] args) {
17         ServerSocket server = null;
18         Socket clientSocket = null;
19         BufferedReader reader = null;
20         PrintWriter writer = null;
21 
22         try {
23             // Create a new socket were we will listen for to connect.
24             server = new ServerSocket(8888);
25 
26             System.out.println("Waiting for input...");
27 
28             // "Block" until connection is made.  (Wait for the connection)
29             clientSocket = server.accept();
30 
31             // Create a new imput reader for reading the data
32             reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
33 
34             // Create a new output writer for writing the data.
35             writer = new PrintWriter(clientSocket.getOutputStream(), true);
36 
37             // Read data from client while client is still attached and
38             // does not send the string "QUIT".
39             String inputLine;
40             while (!(inputLine = reader.readLine()).equalsIgnoreCase("QUIT")) {
41                 System.out.println("SERVER (Data from clinet)> " + inputLine);
42                 writer.write("SERVER SAYS: " + inputLine + "\n");
43             }
44 
45             // The client has told us to quit!
46             System.out.println("DONE READING!");
47 
48         } catch (IOException ex) {
49             System.err.println("Error reading/writing data. " +
50                     "Likely a network problem: " +
51                     ex.getMessage());
52         } finally {
53             try {
54                 // CLOSE EVERYTHING!!!  (Everything that exists, that is.
55                 if (writer != null)
56                     writer.close();
57                 if (reader != null)
58                     reader.close();
59                 if (clientSocket != null)
60                     clientSocket.close();
61                 if (server != null)
62                     server.close();
63             } catch (IOException ex) {
64                 // Well... we did our best...
65                 System.err.println("Failed while failing! " + ex);
66             }
67         }
68     }
69 }