Java Reference
In-Depth Information
Solution
Create a
ServerSocket
and write some code that “speaks” the particular protocol. Or, better,
use a Java-powered web server such as Apache Tomcat or a Java Enterprise Edition (Java
EE) server such as JBoss WildFly.
Discussion
You can implement your own HTTP protocol server for very simple applications, which
we'll do here. For any serious development, you want to use the Java Enterprise Edition; see
the note at the beginning of this chapter.
This example just constructs a
ServerSocket
and listens on it. When connections come in,
they are replied to using the HTTP protocol. So it is somewhat more involved than the
complete web server; the filename in the request is ignored, and a standard message is al-
ways returned. This is thus a
very
simple web server; it follows only the bare minimum of
the HTTP protocol needed to send its response back. A somewhat more complete example is
presented in
Program: Threaded Network Server
, after the issues of multithreading have been
covered. For a real web server written in Java, get Tomcat from the
Apache Tomcat website
.
The code shown in
Example 16-8
,
however, is enough to understand how to structure a
simple server that communicates using a protocol.
Example 16-8. WebServer0.java
public
public class
class
WebServer0
WebServer0
{
public
public static
static final
final
int
int
HTTP
=
80
;
public
public static
final
String CRLF
=
"\r\n"
;
ServerSocket s
;
static
static final
static final
final
String VIEW_SOURCE_URL
=
"https://github.com/IanDarwin/javasrc/tree/master/src/main/java/network"
;
/**
* Main method, just creates a server and call its runServer().
*/
public
public static
throws
Exception
{
System
.
out
.
println
(
"DarwinSys JavaWeb Server 0.0 starting..."
);
WebServer0 w
=
new
static
void
void
main
(
String
[]
argv
)
throws
new
WebServer0
();
w
.
runServer
(
HTTP
);
// never returns!!
}
/** Get the actual ServerSocket; deferred until after Constructor
* so subclass can mess with ServerSocketFactory (e.g., to do SSL).