I’m trying to write a simplest java web server program following an instruction which is only able to handle GET inquiry. The main idea is to get an ObjectOutputStream from a socket, use an ObjectInputStream to open a local file and write it into the ObjectOutputStream byte by byte.
The serve() is attached below. It takes an ObjectOutputStream I want to write to and the path to a file as parameters.
public void serve(ObjectOutputStream out, String path) throws IOException {
System.out.println("Trying to serve: " + path);
File file = new File(path);
if (!file.exists()) {
//return an HTTP 404
} else {
out.writeBytes("HTTP/1.1 200 OK\n\n");
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
int data;
while ((data = in.readByte()) != -1) {
out.writeByte((byte) data);
}
System.out.println("Request valid.");
} catch (IOException e) {
System.out.println("Error in serve(): sending file: " + e.getMessage());
} finally {
if (null != in)
in.close();
}
}
}
However, when I use browser to access localhost:8080 (the port is at 8080), it throws an IOException
invalid stream header: 3C68746D
I believe it’s in out.writeByte((byte) data); step. Can you tell me why and how to fix it? Thanks ahead.
ObjectInputStreamandObjectOutputStreamare used for object serialization in java.Please refer the below article to understand the usage of these streams.
http://java.sun.com/developer/technicalArticles/Programming/serialization/
For your code, you could better use
BufferedInputStreamandBufferedOutputStreamwherever you find corresponding Object Stream.