【问题标题】:localhost works in Edge but not in Chromelocalhost 在 Edge 中有效,但在 Chrome 中无效
【发布时间】:2023-03-22 16:52:01
【问题描述】:

我正在做一个在线 Java 课程并创建了一个非常简单的服务器。使用 Edge 作为客户端它可以工作,但不能与 Chrome 一起使用。我试过关闭防火墙和这里 (WAMP server localhost wont work with Chrome) 和其他地方建议的一些东西,但它们似乎都是对 Windows 文件的过于复杂的更改。肯定有配置设置吗?!

在 Edge 中很好,在 Chrome 中,无论我使用 localhost:999 还是 127.0.0.1:999,它都会返回这个。我也尝试过其他端口。

此页面无法正常工作 127.0.0.1 发送了无效响应。 ERR_INVALID_HTTP_RESPONSE

这是我的代码,以备不时之需。

public static void main(String[] args) {
    try (
        ServerSocket aServer = new ServerSocket(999);
        Socket cn = aServer.accept();
         BufferedReader bis = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        BufferedOutputStream bos = new BufferedOutputStream(cn.getOutputStream());)

        {
            String line = bis.readLine();
        while(line != null && !line.equals(""))
        {
            System.out.println(line);
            line = bis.readLine();
        }

        bos.write("Hello from java TCP Server!".getBytes());

    } catch (IOException ex) {
        System.out.println("Error in connnection: " + ex.getMessage());
    }
}

任何帮助表示赞赏。

【问题讨论】:

  • 如果您要从 HTTP 浏览器使用服务器,您必须返回正确的 HTTP 响应。也就是说,服务器的第一行应该是200 OK,然后是headers,然后是body。 Edge 可能对此很宽容,但 Chrome 需要正确的 HTTP。如果你想要简单的 TCP/IP,不要使用 Chrome,而是使用 telnet 之类的。
  • 谢谢。猜猜我已经找到了 Edge 的用途!

标签: java google-chrome


【解决方案1】:

Web 浏览器要求服务器使用 HTTP 协议。正确的服务器响应是:

BufferedOutputStream bos = new BufferedOutputStream(System.out);

byte[] message="Hello from java TCP Server!".getBytes();

bos.write("HTTP/1.1 200 OK\r\n".getBytes());
bos.write("Content-Type: text/plain\r\n".getBytes());
bos.write(("Content-Length: "+message.length+"\r\n").getBytes());
bos.write("\r\n".getBytes()); // empty line between HTTP header and HTTP content
bos.write(message);

您可以使用另一个使用普通 TCP 套接字的工具来测试您的程序。我推荐“Netcat”(命令:nc)。 Windows 版下载:http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2016-01-26
    • 2016-02-19
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多