gpt4 book ai didi

java - 编写一个简单的 HTTP 服务器来接受 GET 请求

转载 作者:行者123 更新时间:2023-11-29 09:00:00 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的服务器来接受请求,然后将文件的内容写入发送请求的浏览器。服务器连接并写入套接字。但是我的浏览器显示

no data received

并且不显示任何内容。

public class Main {

/**
* @param args
*/
public static void main(String[] args) throws IOException{

while(true){
ServerSocket serverSock = new ServerSocket(6789);
Socket sock = serverSock.accept();

System.out.println("connected");

InputStream sis = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(sis));
String request = br.readLine(); // Now you get GET index.html HTTP/1.1`
String[] requestParam = request.split(" ");
String path = requestParam[1];

System.out.println(path);

PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
File file = new File(path);
BufferedReader bfr = null;
String s = "Hi";

if (!file.exists() || !file.isFile()) {
System.out.println("writing not found...");
out.write("HTTP/1.0 200 OK\r\n");
out.write(new Date() + "\r\n");
out.write("Content-Type: text/html");
out.write("Content length: " + s.length() + "\r\n");
out.write(s);
}else{
FileReader fr = new FileReader(file);
bfr = new BufferedReader(fr);
String line;
while ((line = bfr.readLine()) != null) {
out.write(line);
}
}
if(bfr != null){
bfr.close();
}
br.close();
out.close();
serverSock.close();
}
}

}

最佳答案

如果我使用,你的代码对我有用(数据显示在浏览器中)

http://localhost:6789/etc/hosts

还有一个文件 /etc/hosts(Linux 文件系统符号)。


如果文件不存在,则这段代码

out.write("HTTP/1.0 200 OK\r\n");
out.write(new Date() + "\r\n");
out.write("Content-Type: text/html\r\n");
out.write("\r\n");
out.write("File " + file + " not found\r\n");
out.flush();

将返回显示在浏览器中的数据:请注意,我已在此处明确添加了对 flush() 的调用。确保 out 在其他情况下也被刷新。

另一种可能性是重新排列您的close 语句。引用 EJP 在 How to close a socket 上的回答:

You should close the outermost output stream you have created from the socket. That will flush it.

如果最外层的输出流是(同一来源的另一引述),情况尤其如此:

a buffered output stream, or a stream wrapped around one. If you don't close that, it won't be flushed.

所以 out.close() 应该在 br.close() 之前调用。

关于java - 编写一个简单的 HTTP 服务器来接受 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036662/

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