Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么浏览器上的URI会导致套接字运行三次_Java_Sockets - Fatal编程技术网

Java 为什么浏览器上的URI会导致套接字运行三次

Java 为什么浏览器上的URI会导致套接字运行三次,java,sockets,Java,Sockets,这是一个简单的聊天服务器。 如果我运行并键入:localhost:9092,我会得到打印语句,每次打印三次。 我希望他们只打印一次。 有人能解释一下为什么只键入一次localhost:9092会导致while循环运行三次吗 public class ChatServer { public static void main(String[] args) throws IOException, InterruptedException { ServerSocket serv

这是一个简单的聊天服务器。 如果我运行并键入:localhost:9092,我会得到打印语句,每次打印三次。 我希望他们只打印一次。 有人能解释一下为什么只键入一次localhost:9092会导致while循环运行三次吗

public class ChatServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        PrintWriter pw = null;

        try {
            serverSocket = new ServerSocket(9092);
            while (true) {
                socket = serverSocket.accept();
                System.out.println("--- socket properties: " +  socket.getPort());
                pw = new PrintWriter(socket.getOutputStream(), true);
                pw.println("<font size=\"3\" color=\"red\">This is sme text!</font>");
                pw.println("<font size=\"3\" color=\"green\">This is some text!</font>");
                pw.close();
                socket.close();
                System.out.println("----- someone entered.");
            }
        } finally {
            if (serverSocket != null)
            serverSocket.close();
        }
    }
}

尝试打印发送给您的内容。您会发现它由单独的GET请求组成,可能针对不同的资源。

您没有使用正确的HTTP协议进行响应,因此客户端在放弃之前会尝试3次。HTTP和HTML不一样。。。对HTTP协议进行一些研究,以便您知道html前面需要什么类型的头和信息,以便客户端知道您在说什么。

您是否在浏览器中键入localhost:9092?可能是因为您的服务器没有使用正确的HTTP协议响应,所以浏览器发送了三次。请尝试通过按浏览器上的
F12
,转到
Net/Network
选项卡,在浏览器控制台中跟踪发送到服务器的请求数量,然后在地址栏中键入url并监视
Net
选项卡。
--- socket properties: 61802
----- someone entered.
--- socket properties: 61803
----- someone entered.
--- socket properties: 61804
----- someone entered.