-1

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.

Rustam A.
  • 809
  • 8
  • 15
  • This code cannot possibly accept more than one query, or print more than one line. You need a loop around all the I/O starting from the `accept()` and ending with the missing `close()`. If you didn't see Q1 you directed it to the wrong host. – user207421 Mar 27 '19 at 11:10
  • I know it cannot accept more than one query. This is made intentionally to locate problem. Which is: first connection is lost. I've directed the query to the same hosts - I've done it about 30 times with the same result. Do you say this code prints you Q1 ? – Rustam A. Mar 27 '19 at 11:49

1 Answers1

0

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.

Rustam A.
  • 809
  • 8
  • 15