gpt4 book ai didi

java - 监听 HTTP 请求的正确方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 16:11:32 26 4
gpt4 key购买 nike

我已经编写了一个非常简单、相当低级别的 HTTP(好吧,HTTP 的一部分)服务器作为练习,以更加熟悉我一直在避免的整个 Web 事物。它在第一次尝试时工作得相当好(不是我会推荐任何人实际使用它,但它会按照我的要求去做)。现在的问题是 GET 操作经常失败(刷新有帮助,但不是很好 - 详情如下),我认为这是因为我读取请求的方式(我相当确定我的路由有效):

void start()
{
//...
try(ServerSocket webSock = new ServerSocket(47000) {
//...
while(running) {
try {
Socket sock = webSock.accept();
//read/write from/to sock
}
//...
Thread.sleep(10);
}
}
}

(完整代码在这里:http://pastebin.com/5B1ZuusH)

虽然我不确定什么我做错了。

我确实得到了错误:

This webpage is not available
The webpage at http://localhost:47000/ might be temporarily down or it may have moved permanently to a new web address.
Error 15 (net::ERR_SOCKET_NOT_CONNECTED): Unknown error.

相当多(整个页面未加载),有时脚本或图像也未加载。如果需要,我可以发布整个代码,但其余大部分是样板文件。

最佳答案

[另一个更新]

好吧,澄清一下我的回答,这是一个简单的网络服务器,展示了如何读取 GET 请求。请注意,它在同一个连接中处理多个请求。如果连接关闭,程序将退出。通常,在连接关闭和程序退出之前,我可以从同一个 Web 浏览器发送多个请求。这意味着您不能使用流结束作为消息结束的信号。

请注意,我从不使用手写的网络服务器来做任何真实的事情。我最喜欢的是 Tomcat,但其他框架也很好。

public class MyWebServer
{
public static void main(String[] args) throws Exception
{
ServerSocket server = new ServerSocket(47000);
Socket conn = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

// don't use buffered writer because we need to write both "text" and "binary"
OutputStream out = conn.getOutputStream();
int count = 0;
while (true)
{
count++;
String line = reader.readLine();
if (line == null)
{
System.out.println("Connection closed");
break;
}
System.out.println("" + count + ": " + line);
if (line.equals(""))
{
System.out.println("Writing response...");

// need to construct response bytes first
byte [] response = "<html><body>Hello World</body></html>".getBytes("ASCII");

String statusLine = "HTTP/1.1 200 OK\r\n";
out.write(statusLine.getBytes("ASCII"));

String contentLength = "Content-Length: " + response.length + "\r\n";
out.write(contentLength.getBytes("ASCII"));

// signal end of headers
out.write( "\r\n".getBytes("ASCII"));

// write actual response and flush
out.write(response);
out.flush();
}
}
}
}

[原始响应]

What is the proper way to listen to HTTP requests?

对于我们大多数人来说,正确的方法是使用设计良好的 Web 服务器框架,例如 Tomcat , Jetty , 或 Netty

as an exercise to get more familiar with this whole web thing

但是,如果这是学习 HTTP 的学术练习,那么首先要做的是研究 HTTP 协议(protocol)(​​参见 http://www.w3.org/Protocols/rfc2616/rfc2616.html)。我很确定你没有这样做,因为你的代码没有尝试识别起始行、标题等来确定 GET 请求何时完成以及发送响应是有意义的。

[更新]

很酷。您已经了解了 TCP 如何面向流并且不保留消息边界。是的,应用程序必须处理它。这是最后一个想法 - 如果您使用 readLine 读取起始行和标题,您可能会让您的实验相当可靠地工作 - 只有 GET 请求请注意。当你得到一个空行时,请求就完成了。这将导致缓冲阅读器在正确的时间阻塞,以便您获得所有内容。

这不适用于 POST 等,因为您随后需要解析 Content-Length header 并读取一些字节数。

希望当您意识到正确和可靠地执行此操作涉及多少内容时,这个实验会让您更加欣赏 Jetty - 所以我认为这是一项值得的努力。

关于java - 监听 HTTP 请求的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551803/

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