简体   繁体   English

HTTP 响应 java

[英]HTTP Response java

I am building a HTTP Server in java我正在 java 中构建 HTTP 服务器

The problem is that the browser (Chrome) says that it can't connect to the server after waiting some time.问题是浏览器(Chrome)说它在等待一段时间后无法连接到服务器。 until the timeout直到超时

it's like the browser doesn't get the response back.就像浏览器没有得到响应一样。

I tried我试过了

  • Using different ways to write the response使用不同的方式编写响应
  • Using a different port使用不同的端口

The code i use for sending the response is:我用于发送响应的代码是:

        BufferedOutputStream writer = new BufferedOutputStream(outputStream);
        String CRLF = HTTPServer.CRLF;
        
        try (writer) {
            writer.write((this.getResponseLine() + CRLF).getBytes());
    
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                writer.write((entry.getKey() + ": " + entry.getValue() + CRLF).getBytes());
            }
            writer.write(CRLF.getBytes());
            
            writer.write(this.getResponseBody());
            writer.flush();
        } catch (IOException e) {
            throw e;
        }

The headers are this:标题是这样的:

return new HashMap<>() {{
           put("Content-Length", Integer.toString(content.length));
           put("Date", new Date().toString());
           put("Content-Type", contentMimeType.trim() + "; charset=" + HTTPServer.DEFAULT_CHARSET.displayName());
           put("Server", "Steampunk");
           put("Host", "localhost");
}};

to accept/handle the client i use a ServerSocket .接受/处理客户端我使用ServerSocket

ss = new ServerSocket();
ss.bind(new InetSocketAddress("localhost", operatingPort));

If you mean to access this server from other machines try:如果您打算从其他机器访问此服务器,请尝试:

ss.bind(new InetSocketAddress("0.0.0.0", operatingPort));

That will listen on all interfaces and not restrict connections to the local machine as 'localhost' does.这将侦听所有接口,而不是像“localhost”那样限制与本地计算机的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM