Java Reference
In-Depth Information
* @param port The port number to listen on
*/
protected
protected
ServerSocket
getServerSocket
(
int
int
port
)
throws
throws
Exception
{
return
return new
new
ServerSocket
(
port
);
}
/** RunServer accepts connections and passes each one to handler. */
public
public
void
void
runServer
(
int
int
port
)
throws
throws
Exception
{
s
=
getServerSocket
(
port
);
while
while
(
true
true
) {
try
try
{
Socket us
=
s
.
accept
();
Handler
(
us
);
}
catch
catch
(
IOException e
) {
System
.
err
.
println
(
e
);
return
return
;
}
}
}
/** Handler() handles one conversation with a Web client.
* This is the only part of the program that "knows" HTTP.
*/
public
public
void
void
Handler
(
Socket s
) {
BufferedReader is
;
// inputStream, from Viewer
PrintWriter os
;
// outputStream, to Viewer
String request
;
// what Viewer sends us.
try
try
{
String from
=
s
.
getInetAddress
().
toString
();
System
.
out
.
println
(
"Accepted connection from "
+
from
);
is
=
new
new
BufferedReader
(
new
new
InputStreamReader
(
s
.
getInputStream
()));
request
=
is
.
readLine
();
System
.
out
.
println
(
"Request: "
+
request
);
os
=
new
true
);
os
.
print
(
"HTTP/1.0 200 Here is your data"
+
CRLF
);
os
.
print
(
"Content-type: text/html"
+
CRLF
);
os
.
print
(
"Server-name: DarwinSys NULL Java WebServer 0"
+
CRLF
);
String reply1
=
"<html><head>"
+
"<title>Wrong System Reached</title></head>\n"
+
"<h1>Welcome, "
;
String reply2
=
", but...</h1>\n"
+
"<p>You have reached a desktop machine "
+
"that does not run a real Web service.\n"
+
"<p>Please pick another system!</p>\n"
+
new
PrintWriter
(
s
.
getOutputStream
(),
true