为什么代码最后一句话不执行?
package com.tomcat.main;
import
java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.
UnknownHostException;
import com.tomcat.pojo.Request;
import com.tomcat.pojo.Response;
public class HttpServer {
private ServerSocket serverSocket;
public HttpServer() throws Exception{
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("127.0.0.1", 8080));
}
public void await() throws Exception{
while(true){
Socket socket = serverSocket.accept();
System.out.println(socket.getPort());
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
Request request = new Request(inputStream);
request.parseInputStream();
}
}
public static void main(String[] args) throws Exception{
HttpServer httpServer = new HttpServer();
httpServer.await();
}
}
package com.tomcat.pojo;
import java.io.BufferedReader;
import java.io.
IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Request {
private InputStream inputStream;
private String context;
public Request(InputStream inputStream){
this.inputStream =inputStream;
context = new String();
}
public void parseInputStream() throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
int c = -1;
while((c = reader.read())!=-1){
builder.append((char)c);
}
System.out.println(builder.toString());
}
}
上面是代码,为什么request类中的parseInputStream中的System.out.println(builder.toString());
没有执行,没有报错,问题出在哪里
------解决方案--------------------while((c = reader.read())!=-1){
builder.append((char)c);
} 这句有问题,这个循环里面存在阻塞。reader这个输入流永远也不会结束,只有当服务器回复了客户端的请求时,这个流才有可能结束。如果你仅仅是想输出请求头的内容 改成while((c = reader.read())!=-1){
System.out.pritnln((char)c);}应该就可以了。