正如好奇心我正在编写一个测试HTTP服务器,它将接受来自浏览器应用程序的请求并基于简单的服务器套接字模型向其发送响应。
我有两种发送HTTP方法的方法:sendHttpResponse1()
& sendHttpResponse2()
,基本上从文件中读取:httpResponse.txt
(包含HTTP响应标头+ HTML代码,请参阅下面的文件内容)
并通过套接字连接向客户端发送响应。
我在使用主方法时使用其中一种方法,同时发送响应。
这两种方法的行为都不符合我的预期。
我的代码是:
import java.io.*;
import java.net.*;
public class TestHttpServer {
public static void main(String[] args) {
try {
ServerSocket sruSoc = new ServerSocket(8333);
Socket clientConnection = sruSoc.accept();
InputStream is = clientConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 100);
while((message=br.readLine())!=null){
System.out.println(message);
if(message.isEmpty()){
break;
}
}
System.out.println("Request received");
sendHttpResponse2(clientConnection);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void sendHttpResponse1(Socket clientConnection)
throws IOException, FileNotFoundException {
PrintWriter pw = new PrintWriter(clientConnection.getOutputStream());
File file = new File("httpResponse.txt");
FileInputStream fis = new FileInputStream(file);
byte[] buff = new byte[50];
System.out.println("\nThis is what client will see");
System.out.println();
while(fis.read(buff)!=-1){
String lineB = new String(buff);
pw.write(lineB);
System.out.println(lineB);
}
fis.close();
pw.close();
}
private static void sendHttpResponse2(Socket clientConnection)
throws IOException, FileNotFoundException {
PrintWriter pw = new PrintWriter(clientConnection.getOutputStream());
File file = new File("resources/httpResponse/httpResponse.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println("\nThis is what client will see");
System.out.println();
String line=null;
while((line = reader.readLine())!=null){
pw.write(line);
System.out.println(line);
}
reader.close();
//pw.flush();
pw.close();
}
}
文件:httpResponse.txt
HTTP/1.1 200 OK
Date: Mon, 20 Apr 2015 22:38:34 GMT
Server: Test/0.1 (Java)
Content-Type: text/html;
Accept-Charset: iso-8859-5, unicode-1-1;q=0.8
Accept-Ranges: none
Connection: close
<html>
<head>
<title>An Example Page</title>
</head>
<body>
<b>Hello World</b>, this is a very simple HTML document.
</body>
</html>
sendHttpResponse1()
的输出:
Hello World, this is a very simple HTML document. is a very si
sendHttpResponse2()
的输出:
没有回应,空浏览器。
请在上述两种方法中建议我做错了什么? 我做了很多突破,但似乎我做了一些愚蠢的错误,这没有给我预期的输出。 任何帮助将不胜感激。
答案 0 :(得分:0)
最后我得到了答案:基础知识: 在sendHttpResponse2中: 引起问题的那一行是:byte [] buff = new byte [50]; 固定大小的字节数组,因此输出正确。
在sendHttpResponse2中: 它应该是println而不是write()。