Java Reference
In-Depth Information
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import org.simpleframework.http.core.ContainerSocketProcessor;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;
public class HTTPServer implements Container {
public void handle(Request request, Response response) {
try {
PrintStream body = response.getPrintStream();
response.setValue("Content-Type", "text/plain");
body.println("Hello there, you've requested: "+request.getPath());
body.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] list) throws Exception {
// If you get an Address already in use: bind error, try changing the port
int port = 880;
Container container = new HTTPServer();
ContainerSocketProcessor server = new ContainerSocketProcessor(container);
Connection connection = new SocketConnection(server);
SocketAddress address = new InetSocketAddress(port);
connection.connect(address);
Desktop.getDesktop().browse(new URI(" http://127.0.0.1:" + port));
System.out.println("Press ENTER to stop server...");
System.in.read();
connection.close();
server.stop();
}
}
Run the code. A web browser will open and connect you to a running HTTP server. Try modify-
ing the URL (e.g., http://127.0.0.1:880/test/me ) and note that the server changes its response
accordingly. See Figure 10-31.
You can easily extend this class with what you've learned in the chapter on working with files to
open and transmit HTML and other files stored on the server to the browser. The following class
shows you how to do so:
import java.awt.Desktop;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.nio.file.Files;
Search WWH ::




Custom Search