Skip to content
Snippets Groups Projects
TcpExample1Telnet.java 5.19 KiB
package TcpExamples;

import java.io.*;
import java.net.*;

/**
 * <p>
 * The simplest possible TCP network program, opening a socket and waiting for a reply. 
 * It listens for any socket connection response, either from telnet (telnet localhost 2317)
 * or another program that you write (which we will do later). 
 * Once a socket connection is established, TcpExample1Telnet simply
 * writes a string in response to that connection and finishes, exiting.
 * 
 * <p>
 * As an alternative to running the Windows (or other operating system) console, 
 * you can instead run the NetBeans terminal window.  If you are on Windows,
 * NetBeans is looking for Cygwin installation (for Unix-like compatibility)
 * with details at <a href="https://savage.nps.edu/Savage/developers.html#Cygwin" target="blank">Savage Developers Guide: Cygwin</a>.
 * Modifying this program is the basis for Assignment 1.
 * </p>
 * 
 * <p>
 * Testing the running server program from telnet looks like this:
 * </p>
 * <pre>
 * it154916:projects mcgredo$ <b>telnet localhost 2317</b>
 * Trying ::1...
 * Connected to localhost.
 * Escape character is '^]'.
 * This was written by the server
 * Connection closed by foreign host.
 * </pre>
 * <p>
 * Notice that "This was written by the server" matches 
 * what is written by the code below, over the output stream.
 * </p>
 * 
 * <p>
 * After this first connection the program below drops to
 * the bottom of the method, and does not repeat itself.
 * In other words, the program exits.
 * </p>
 * 
 * @see <a href="../../../src/TcpExamples/TcpExample1TerminalLog.txt" target="_blank">TcpExample1TerminalLog.txt</a>
 * @see <a href="../../../src/TcpExamples/TcpExample1NetBeansConsoleTelnet.png" target="_blank">TcpExample1NetBeansConsoleTelnet.png</a>
 * @see <a href="../../../src/TcpExamples/TcpExample1NetBeansConsoleTelnet.pdf" target="_blank">TcpExample1NetBeansConsoleTelnet.pdf</a>
 * @see <a href="../../../src/TcpExamples/TcpExample1ScreenshotNetcat.png" target="_blank">TcpExample1ScreenshotNetcat.png</a>
 * @see <a href="../../../src/TcpExamples/TcpExample1ScreenshotTelnet.png" target="_blank">TcpExample1ScreenshotTelnet.png</a>
 * @see <a href="https://savage.nps.edu/Savage/developers.html#Cygwin" target="blank">Savage Developers Guide: Cygwin</a>
 * @see <a href="https://savage.nps.edu/Savage/developers.html#telnet" target="blank">Savage Developers Guide: telnet</a>
 * 
 * @author mcgredo
 * @author brutzman@nps.edu
 */
public class TcpExample1Telnet 
{
    /** Default constructor */
    public TcpExample1Telnet()
    {
        // default constructor
    }
    /**
     * Program invocation, execution starts here
     * @param args command-line arguments
     */
    public static void main(String[] args)
    {
        try
        {
            System.out.println(TcpExample1Telnet.class.getName() + " has started and is waiting for a connection.");
            System.out.println("  help:     https://savage.nps.edu/Savage/developers.html#telnet");
            System.out.println("  terminal: enter (telnet localhost 2317) or, for macOS (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()) // listen, 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 " + TcpExample1Telnet.class.getName()); // to remote client
                System.out.println("This server response was written by server " + TcpExample1Telnet.class.getName()); // 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(TcpExample1Telnet.class.getName() + " completed successfully.");
        }
        catch(IOException ioe)
        {
            System.err.println("Exception with " + TcpExample1Telnet.class.getName() + " networking:"); // describe what is happening
            System.err.println(ioe);
            // 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 (ioe instanceof java.net.BindException)
                System.err.println("*** Be sure to stop any other running instances of programs using this port!");
        }
    }
}