JMU
TCP for Text Transport
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Transmission Control Protocol
Connection-Oriented Protocols
Reliable Protocols
Protocols with Flow Control
The Client-Server Concept
The Server Side

The Process

javaexamples/internet/UppercaseEchoServer.java (Fragment: 1)
                  // Create a server socket to wait for a connection
          ss = new ServerSocket(port);
                // Accept the connection (i.e., complete the handshaking)
                // Note: This method blocks.
                s  = ss.accept();

                // Get an input stream and construct a reader
                in = new BufferedReader(
                   new InputStreamReader(s.getInputStream()));
              
                // Get an output stream and construct a writer
                out = new PrintWriter(s.getOutputStream());
              
                // Read and write to the two streams as required
                // by the application
        
The Client Side

The Process

javaexamples/internet/TCPFileRetriever.java (Fragment: 1)
               // Create a connection to a particular host and port
       s   = new Socket(host, port);
       
       // Get an output stream and construct a writer
       out = new PrintWriter(s.getOutputStream());
       
       // Get an input stream and construct a reader
       in  = new BufferedReader(
                 new InputStreamReader(s.getInputStream()));

              
       // Read and write to the two streams as required
       // by the application
        
ServerSocket Objects and Threads
The Server Side - A Complete Example

An Uppercase Echo Server

javaexamples/internet/UppercaseEchoServer.java
        import java.io.*;
import java.net.*;


/**
 * A single-threaded ECHO server that also converts to uppercase
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class UppercaseEchoServer implements Runnable
{
    private volatile boolean  keepRunning;    
    private BufferedReader    in;
    private int               port;    
    private PrintWriter       out;
    private ServerSocket      ss;
    private Socket            s;
    private Thread            controlThread;
    


    /**
     * Default Constructor
     */
    public UppercaseEchoServer()
    {
       this(9462);
    }


    /**
     * Explicit Value Constructor
     *
     * @param port  The port the server should listen to
     */
    public UppercaseEchoServer(int port)
    {
       this.port = port;       
    }


    /**
     * The code that is executed in the controlThread object's
     * thread of execution
     */
    public void run()
    {
       String    line;

       try
       {
          // Create a server socket to wait for a connection
          ss = new ServerSocket(port);

          // Set the timeout for the accept() method
          ss.setSoTimeout(5000);

          while (keepRunning)
          {
             try
             {
                // Accept the connection (i.e., complete the handshaking)
                // Note: This method blocks.
                s  = ss.accept();

                // Get an input stream and construct a reader
                in = new BufferedReader(
                   new InputStreamReader(s.getInputStream()));
              
                // Get an output stream and construct a writer
                out = new PrintWriter(s.getOutputStream());
              
                // Read and write to the two streams as required
                // by the application

                // In this case, read a line
                line = in.readLine();
                System.out.println(line);
             
                // Convert the line to uppercase and write it out
                out.println(line.toUpperCase());

                // Flush the output stream
                out.flush();

                // Close the socket when done
                s.close();
             }
             catch (SocketTimeoutException ste)
             {
                // The accept() method timed out.  Check to see if
                // the tread should keep running or not.
             }
             catch (IOException ioe) 
             {
                // Had a problem with the Socket.  Start accepting
                // connections again.
             }
          }
       }
       catch (IOException ioe) 
       {
          // Big problem so exit
          ioe.printStackTrace();
          System.exit(1);
       }
    }
    


    /**
     * Start the thread of execution
     */
    public void start()
    {
       if (controlThread == null)
       {
          controlThread = new Thread(this);
          keepRunning = true;

          controlThread.start();
       }
    }
    


    /**
     * Stop the thread of execution (after it finishes the
     * current connection)
     */
    public void stop()
    {
       keepRunning = false;
    }



}
        

The Driver

javaexamples/internet/UppercaseEchoServerDriver.java
        import java.io.*;


/**
 * A single-threaded ECHO server that also converts to uppercase
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class UppercaseEchoServerDriver
{

    /**
     * Entry point of the application
     *
     * @param args    The command-line arguments
     */
    public static void main(String[] args)
    {
       BufferedReader        in;       
       UppercaseEchoServer   server;


       in = new BufferedReader(new InputStreamReader(System.in));
       
       // Construct and start the server
       server = new UppercaseEchoServer(9462);
       server.start();

       System.out.println("Press [Enter] to stop the server...");

       try
       {
          // Block until the user presses [Enter]
          in.readLine();
       }
       catch (IOException ioe)
       {
          System.out.println("  Stopping because of an IOException");
       }

       // Stop the server
       server.stop();
    }




}