gpt4 book ai didi

java - Printwriter 不写入 outputStream

转载 作者:行者123 更新时间:2023-12-03 23:11:34 25 4
gpt4 key购买 nike

我正在尝试用 Java 实现一个基本的网络服务器。当我将 Web 浏览器定向到 127.0.0.1:8020/webpage.html 时,服务器会收到请求 header ,但当它尝试发回网页时,它不会显示在浏览器上。

有人能帮忙吗?

public class WebServer
{
public static void main(String[] args)
{

try
{
ExecutorService scheduler = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8020);
while (true)
{
Socket client = server.accept();
Runnable r = new HTTPThread(client.getInputStream(), client.getOutputStream());
scheduler.execute(r);
System.out.println("LOG: New Thread Created");
}
}
catch (IOException e)
{
System.out.println("ERROR: Cannot listen on socket");
e.printStackTrace();
}
}
}


public class HTTPThread implements Runnable {
InputStream in;
OutputStream out;

private String fileName;
private String fileLoc;
private static final String rootLoc = "C:\\Users\\myName\\workspace\\HTTPServer\\src\\";

HTTPThread(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}

public void run() {
try {

// show request headers and store http header
System.out.println("LOG: Preparing to read request");
String header = readInput(in);
System.out.println("LOG: Request read successfully!");
System.out.println(header);


// get file name from request header
fileLoc = rootLoc + header.substring(5, header.indexOf("H") - 1);
System.out.println(fileLoc);


PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));

//send response header and body
writer.print("HTTP/1.0 200 OK\nContent-Type: text/html\n\n" + fileReader(fileLoc));
System.out.println("LOG: Response Sent");

out.close();
in.close();
}

catch (IOException e) {
System.out.println("ERROR: Could not listen on socket");
System.exit(-1);
}

}

//Returns content of webpage as a string (html)
public String fileReader(String file) {

StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner;
try {
scanner = new Scanner(new FileInputStream(file));
while (scanner.hasNextLine()) {
text.append(scanner.nextLine() + NL);
}

return text.toString();
} catch (FileNotFoundException e) {
System.out.println("ERROR: File Not Found");
System.exit(-1);
return null;
}
}

//Reads bytestream from client and returns a string
private String readInput(InputStream is) {

BufferedReader in = new BufferedReader(new InputStreamReader(is));
try
{
String current;
String header = "";
while (!(current = in.readLine()).isEmpty())
{
header += current + System.getProperty("line.separator");
}

return header;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}

最佳答案

out.close(); 之前添加 writer.close(); 将修复它。

关于java - Printwriter 不写入 outputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com