Subversion Repositories programming

Rev

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