Subversion Repositories programming

Rev

Rev 187 | Rev 189 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
186 ira 1
/*******************************************************************************
2
 * File: P1Server.java
3
 * Author: Ira W. Snyder (devel@irasnyder.com)
4
 * Class: CS380 - Computer Networking
5
 *
6
 * Assignment: Project #1
7
 * Date Last Modified: 2006-01-18
8
 *
9
 * Purpose: Opens a listening TCP Socket on port 1337. It echoes back
10
 *          every packet that it recieves.
11
 *
12
 ******************************************************************************/
13
 
14
import java.io.*;
15
import java.net.*;
16
 
17
public class P1Server
18
{
187 ira 19
    public static final int portNumber = 1337;
188 ira 20
    public static final String exitSeq = "QUIT";
186 ira 21
 
187 ira 22
    /**
23
     * Method: main()
24
     * Purpose: This method creates a listening socket on port 1337 and
25
     * accepts the first connection made to it. It then echoes back anything
26
     * sent to it, until it recieves a "QUIT", at which point it terminates.
27
     */
186 ira 28
    public static void main (String[] args) throws IOException
29
    {
30
        ServerSocket serverSocket = null;
31
 
32
        /* Try to open the port for listening */
33
        try
34
        {
35
            serverSocket = new ServerSocket (portNumber);
36
        }
37
        catch (IOException e)
38
        {
39
            System.err.println ("Could not listen on port: " + portNumber);
40
            System.exit(1);
41
        }
42
 
43
        Socket clientSocket = null;
44
 
45
        /* Try to accept the first connection that comes in */
46
        try
47
        {
48
            clientSocket = serverSocket.accept();
49
        }
50
        catch (IOException e)
51
        {
52
            System.err.println ("Accept failed.");
53
            System.exit(1);
54
        }
55
 
56
        /* Set up input and output streams */
57
        PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
58
        BufferedReader in = new BufferedReader(
59
                                new InputStreamReader(
60
                                    clientSocket.getInputStream()));
61
 
62
        /* Use Strings to hold the input and output */
63
        String inputLine, outputLine;
64
 
65
        /* Read input and echo back to output */
66
        while ((inputLine = in.readLine()) != null)
67
        {
68
            /* If we recieve a message to quit, do so. */
188 ira 69
            if (inputLine.equals (exitSeq))
186 ira 70
                break;
71
 
72
            /* Echo back what we recieved */
73
            out.println (inputLine);
74
        }
75
 
76
        /* Cleanup */
77
        out.close();
78
        in.close();
79
        clientSocket.close();
80
        serverSocket.close();
81
    }
82
}
83