我正在编写一个网络编程类的第一个家庭作业项目,它是用Java编写一个简单的Web服务器。我处于传输数据的地步,对于未经训练的人来说,我的宝贝服务器似乎工作正常。但是,我无法找到发送适当响应的方法。 (换句话说,一个无效的页面请求会显示一个404-ish的HTML页面,但是当我查看响应头时,它仍然会返回200 OK状态)。如何仅使用标准网络库发送HTTP响应?
我仅限于能够使用标准网络库进行套接字管理和标准I/O库来读取和写入输入流中的字节和字符串。下面是一些相关的代码:
从我的主...
ServerSocket servSocket = new ServerSocket(port, 10); // Bind the socket to the port
System.out.println("Opened port " + port + " successfully!");
while(true) {
//Accept the incoming socket, which means that the server process will
//wait until the client connects, then prepare to handle client commands
Socket newDataSocket = servSocket.accept();
System.out.println("Client socket created and connected to server socket...");
handleClient(newDataSocket); //Call handleClient method
}
从handleClient方法......(一个循环内部解析请求方法和路径)
if(checkURL.compareTo("/status") == 0) { // Check to see if status page has been requested
System.out.println("STATUS PAGE"); // TEMPORARY. JUST TO MAKE SURE WE ARE PROPERLY ACCESSING STATUS PAGE
sendFile("/status.html", dataStream);
}
else {
sendFile(checkURL, dataStream); // If not status, just try the input as a file name
}
从SENDFILE方法...
File f = new File(where); // Create the file object
if(f.exists() == true) { // Test if the file even exists so we can handle a 404 if not.
DataInputStream din;
try {
din = new DataInputStream(new FileInputStream(f));
int len = (int) f.length(); // Gets length of file in bytes
byte[] buf = new byte[len];
din.readFully(buf);
writer.write("HTTP/1.1 200 OK\r\n"); // Return status code for OK (200)
writer.write("Content-Length: " + len + "\r\n"); // WAS WRITING TO THE WRONG STREAM BEFORE!
writer.write("Content-Type: "+type+"\r\n\r\n\r\n"); // TODO VERIFY NEW CONTENT-TYPE CODE
out.write(buf); // Writes the FILE contents to the client
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); // Not really handled since that's not part of project spec, strictly for debug.
}
}
else {
writer.write("HTTP/1.1 404 Not Found\r\n"); // Attempting to handle 404 as simple as possible.
writer.write("Content-Type: text/html\r\n\r\n\r\n");
sendFile("/404.html", sock);
}
任何人都可以解释如何,在条件从sendFile,我可以改变404块中的响应(就像我之前说的,响应头仍然显示200 OK)?这是对我的废话,我只是想使用HTTPResponse类,但我不能。 (另外,如果f.exists == true,则不显示内容长度和类型。)
谢谢!
在我们没有看到的代码中,是否曾经将writer变量添加到输出流中?另外什么数据类型是作家和出? (我不想假设) – Sean 2010-09-12 23:22:51
@gameaddict:我有PrintWriter作家=新的PrintWriter(sock.getOutputStream());在方法的最开始。对不起,不要试图保持简洁!另外,作家是PrintWriter,出来的是DataOutputStream。 – rownage 2010-09-12 23:32:37
尝试从作者更改标题,并将其放入字符串中。然后将其添加到字符串格式的outputStream中。看看是否有帮助。你也可能想看看不要从你的其他地方调用sendFile()。如果没有找到404.html,你可能会以无限循环结束。你可以在...中做到这一点...如果(文件存在)文件是你传入的文件,否则文件是404文件.....然后做你的尝试。 – Sean 2010-09-13 00:30:51