Subversion Repositories programming

Rev

Rev 186 | Rev 188 | 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;
186 ira 20
 
187 ira 21
    /**
22
     * Method: main()
23
     * Purpose: This method creates a listening socket on port 1337 and
24
     * accepts the first connection made to it. It then echoes back anything
25
     * sent to it, until it recieves a "QUIT", at which point it terminates.
26
     */
186 ira 27
    public static void main (String[] args) throws IOException
28
    {
29
        ServerSocket serverSocket = null;
30
 
31
        /* Try to open the port for listening */
32
        try
33
        {
34
            serverSocket = new ServerSocket (portNumber);
35
        }
36
        catch (IOException e)
37
        {
38
            System.err.println ("Could not listen on port: " + portNumber);
39
            System.exit(1);
40
        }
41
 
42
        Socket clientSocket = null;
43
 
44
        /* Try to accept the first connection that comes in */
45
        try
46
        {
47
            clientSocket = serverSocket.accept();
48
        }
49
        catch (IOException e)
50
        {
51
            System.err.println ("Accept failed.");
52
            System.exit(1);
53
        }
54
 
55
        /* Set up input and output streams */
56
        PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
57
        BufferedReader in = new BufferedReader(
58
                                new InputStreamReader(
59
                                    clientSocket.getInputStream()));
60
 
61
        /* Use Strings to hold the input and output */
62
        String inputLine, outputLine;
63
 
64
        /* Read input and echo back to output */
65
        while ((inputLine = in.readLine()) != null)
66
        {
67
            /* If we recieve a message to quit, do so. */
68
            if (inputLine.equals ("QUIT"))
69
                break;
70
 
71
            /* Echo back what we recieved */
72
            out.println (inputLine);
73
        }
74
 
75
        /* Cleanup */
76
        out.close();
77
        in.close();
78
        clientSocket.close();
79
        serverSocket.close();
80
    }
81
}
82