Subversion Repositories programming

Rev

Rev 189 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*******************************************************************************
 * File: P1Server.java
 * Author: Ira W. Snyder (devel@irasnyder.com)
 * Class: CS380 - Computer Networking
 *
 * Assignment: Project #1
 * Date Last Modified: 2006-01-18
 *
 * Purpose: Opens a listening TCP Socket on port 1337. It echoes back
 *          every packet that it recieves.
 *
 ******************************************************************************/

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

public class P1Server
{
    /* Instance variables */
    public static final int portNumber = 1337;
    public static final String exitSeq = "QUIT";

    /**
     * Method: main
     * Purpose: This method creates a listening socket on port 1337 and
     * accepts the first connection made to it. It then echoes back anything
     * sent to it, until it recieves a "QUIT", at which point it terminates.
     */
    public static void main (String[] args) throws IOException
    {
        ServerSocket serverSocket = null;

        /* Try to open the port for listening */
        try
        {
            serverSocket = new ServerSocket (portNumber);
        }
        catch (IOException e)
        {
            System.err.println ("Could not listen on port: " + portNumber);
            System.exit(1);
        }

        Socket clientSocket = null;

        /* Try to accept the first connection that comes in */
        try
        {
            clientSocket = serverSocket.accept();
        }
        catch (IOException e)
        {
            System.err.println ("Accept failed.");
            System.exit(1);
        }

        /* Set up input and output streams */
        PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                    clientSocket.getInputStream()));

        /* Use Strings to hold the input and output */
        String inputLine, outputLine;

        /* Read input and echo back to output */
        while ((inputLine = in.readLine()) != null)
        {
            /* Echo back what we recieved */
            out.println (inputLine);
            System.out.println ("Recieved a packet");
            
            /* If we recieve a message to quit, do so. */
            if (inputLine.equals (exitSeq))
            {
                System.out.println ("Recieved exitSeq");
                break;
            }
        }

        /* Cleanup */
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}