I’m trying to build a simple HTTP Server using Java, using
java.net.ServerSocket = new ServerSocket(this.port, 0, this.ip);
java.net.Socket connection = null;
connection = server.accept();
java.io.OutputStream out = new BufferedOutputStream(connection.getOutputStream());
when connected using web browser, i’m simply write the output (HTTP headers + html code) from a string
String headers = "http headers";
String response = "this is the response";
out.write(headers.getBytes());
out.write(response.getBytes());
out.flush();
connection.close();
and the browser display it correctly.
And now my problem is, i want to construct a full webpage (html, javascript, css, images) and put those files into the Java package (JAR) file, and of course, those files are designed not-to-be modified after the JAR is ready to use. And here’s the questions:
-
how to achieve this? storing the files inside the JAR and then output them when a connection is made.
-
how output images file (non-text) just like output-ing
Stringbyout.write()?
Thanks, any sample or code is appreciated.
Is implementing an HTTP server your primary problem or just a way to achieve some other goal? If the latter, consider embedding Tomcat or Jetty, much simpler and with standard servlet API.
Back to your question: JAR is just a ZIP file, you can put anything there, including files, images, movies, etc. If you place a file inside a JAR file you can load it easily with:
See these questions for details how
getResourceAsStream()works:About your second question: when you have an
InputStreaminstance you can just read it byte-by-byte and copy to targetoutOutputStream. Of course there are better, safer and faster ways, but that’s beyond the scope of this question. Just have a look at IOUtils.copy():And the last hint concerning your code: if you are sending
Strings , considerOutputStreamWriterandPrintWriterwhich have easier API.