-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebServer.java
More file actions
97 lines (88 loc) · 2.52 KB
/
WebServer.java
File metadata and controls
97 lines (88 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* A simple web server: it creates a new WebWorker for each new client
* connection, so all the WebServer object does is listen on the port
* for incoming client connection requests.
*
* This class contains the application "main()" (see below). At startup,
* main() creates an object of this class (WebServer) and invokes its
* start() method. Since servers run continually, the start() method
* never returns. It uses socket programming to listen for client network
* connection requests. When one happens, it creates a new object of
* the WebWorker class and hands that client connection off to the WebWorker
* object. The WebServer object then just keeps listening for new client
* connections. See the WebWorker source for more information about it.
*
**/
import java.net.*;
public class WebServer
{
private ServerSocket socket;
private boolean running;
/**
* Constructor
**/
private WebServer()
{
running = false;
}
/**
* Web server starting point. This method does not return until
* the server is finished, so perhaps it should be named "runServer"
* or something like that.
* @param port is the TCP port number to accept connections on
**/
private boolean start(int port)
{
Socket workerSocket;
WebWorker worker;
try {
socket = new ServerSocket(port);
} catch (Exception e) {
System.err.println("Error binding to port "+port+": "+e);
return false;
}
while (true) {
try {
// wait and listen for new client connection
workerSocket = socket.accept();
} catch (Exception e) {
System.err.println("No longer accepting: "+e);
break;
}
// have new client connection, so fire off a worker on it
worker = new WebWorker(workerSocket);
new Thread(worker).start();
}
return true;
} // end start
/**
* Does not do anything, since start() never returns.
**/
private boolean stop()
{
return true;
}
/**
* Application main: process command line and start web server; default
* port number is 8080 if not given on command line.
**/
public static void main(String args[])
{
int port = 8080;
if (args.length > 1) {
System.err.println("Usage: java Webserver <portNumber>");
return;
} else if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
System.err.println("Argument must be an int ("+e+")");
return;
}
}
WebServer server = new WebServer();
if (!server.start(port)) {
System.err.println("Execution failed!");
}
} // end main
} // end class