package TcpExamples; import java.io.*; import java.net.*; /** * The simplest possible TCP network program. It listens for * a connection, from telnet (telnet localhost 2317) or a program * you write, which we will do later. Right now the TcpExample simply * writes a string in response to a connection. * * Modifying his program is the basis for Assignment 1. * * Testing the running server program from telnet looks like this: * * it154916:projects mcgredo$ telnet localhost 2317 * Trying ::1... * Connected to localhost. * Escape character is '^]'. * This was written by the server * Connection closed by foreign host. * * Notice that "This was written by the server" matches * what is written by the code below, over the output stream. * * After this first connection the program below drops out * the bottom of the program, and does not repeat itself. * The program exits. * * @author mcgredo * @author brutzman */ public class TcpExample1Telnet { public static void main(String[] args) { try { System.out.println("TcpExample1Telnet has started and is waiting for a connection."); System.out.println(" help: https://savage.nps.edu/Savage/developers.html#telnet"); System.out.println(" enter (telnet localhost 2317) or (nc localhost 2317)..." ); // The ServerSocket waits for a connection from a client. // It returns a Socket object when the connection occurs. ServerSocket serverSocket = new ServerSocket(2317); // Use Java io classes to write text (as opposed to // unknown bytes of some sort) to the client // The Socket object represents the connection between // the server and client, including a full duplex connection try (Socket clientConnection = serverSocket.accept()) // wait here for a client to connect { // OK we got something, time to respond! // Use Java io classes to write text (as opposed to // unknown bytes of some sort) to the client OutputStream os = clientConnection.getOutputStream(); PrintStream ps = new PrintStream(os); ps.println("This client response was written by server TcpExample1."); // to remote clientnc System.out.println("This server response was written by server TcpExample1."); // to server console // "flush()" in important in that it forces a write // across what is in fact a slow connection ps.flush(); } System.out.println("TcpExample1 completed successfully."); } catch(IOException e) { System.err.println("Problem with TcpExample1Telnet networking:"); // describe what is happening System.err.println("Error: " + e); // Provide more helpful information to user if exception occurs due to running twice at one time // brute force exception checking, can be brittle if exception message changes // if (e.getMessage().equals("Address already in use: NET_Bind")) if (e instanceof java.net.BindException) System.err.println("*** Be sure to stop any other running instances of programs using this port!"); } } }