简体   繁体   中英

Why is java ServerSocket loses first connection?

I'm trying to write a very simple java server which is mostly a copy-paste from Oracle tutorial and access it from browser by my LAN IP 192.168.0.106/?Q1.

My program outputs "Ready..." in terminal, but doesn't output the browser query Q1. Then I make second query Q2 to the same IP and program prints it: "GET /?Q2 HTTP/1.1...".

When I'm doing the same query to 127.0.0.1 (Q1 and Q2) surprisingly program outputs "Ready..." on first query, but print "null" on second.

Why am I loosing my first query? Is my in.readLine() causing it? And why when connecting to loopback 127.0.0.1 address I can get connection, but can't get my query printed?

    int portNumber = 80;
    System.out.println("Started...");
    String s="#";

    try ( 
    ServerSocket serverSocket = new ServerSocket(portNumber);
    Socket clientSocket = serverSocket.accept();
    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    ) {
        System.out.println("Ready...");
        s=in.readLine(); /// Let's take first line only
        System.out.println(s);

    } catch(Exception e){
        System.out.println("Error "+e);
    }

I'd like to see first query in output: "GET /?Q1...". Thank you.

Turn out that packets where not lost . Looks like they were rearranged maybe due to stack nature of InputBuffer(or not): first in - last out. And since program was meant to show only one answer, after closing connection with no html data it showed last query that entered queue. The rearrangement was caused by empty tcp packet that chrome ( v73 with Use a prediction service to load pages more quickly turned ON ) sent before actual queries. Since it was empty InputBuffer stayed blocked until this tcp connection was closed. And incoming connections were stacking. Empty connection would be closed by Chrome by timeout in 2 minutes or when page reload happens and next pending connection would be processed. It would be Q2 but it didn't mean Q1 is lost - it just waits for next empty packet to be processed or discarded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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