从Web服务器接收数据

时间:2015-04-04 02:50:53

标签: connection webserver client server

我在实现简单Web服务器的程序中遇到问题。

当我向网络服务器发送HTTP请求时,网络服务器会向客户端发送HTTP代码,但我希望收到=>我有错误"重置连接!)

clientSocket = new Socket("localhost", 1234);

BufferedWriter out = new BufferedWriter(
        new OutputStreamWriter(
                new BufferedOutputStream(clientSocket.getOutputStream()), "UTF-8")
);
out.write(OUTPUT_HEADERS+"GET /"+"home.html" + " HTTP/1.1\nHost:"+clientSocket.getLocalAddress() +"\nUser-agent: Mozilla/5.0\nAccept-language: fa");
out.flush();

System.out.println(" waiting...");

InputStreamReader isr=new InputStreamReader(clientSocket.getInputStream());
BufferedReader br=new BufferedReader(isr);
while (br.ready()) {                
    System.out.println(br.readLine());
}

1 个答案:

答案 0 :(得分:0)

根据HTTP 1.1规范:

http://www.w3.org/Protocols/HTTP/1.1/rfc2616bis/draft-lafon-rfc2616bis-03.html#request

请求和请求标头需要使用CR / LF终止。

即。变化:

out.write(OUTPUT_HEADERS+"GET /"+"home.html" + " HTTP/1.1\nHost:"+clientSocket.getLocalAddress() +"\nUser-agent: Mozilla/5.0\nAccept-language: fa");
out.flush();

out.write(OUTPUT_HEADERS+"GET /"+"home.html" + " HTTP/1.1\r\nHost:"+clientSocket.getLocalAddress() +"\r\nUser-agent: Mozilla/5.0\r\nAccept-language: fa\r\n");
out.write("\r\n");
out.flush();