Struggling with Socket, JSON [Java]

So, I'm trying to build up my knowledge of web, JSON, Javascript fetch, promises, etc., and I'm hating life.

I keep getting either an AbortError from the JS fetch call or a connection reset from a direct connect to http://localhost:8080 in the browser. I've tried as "text/plain" as well as removing extra newlines, calling flush() on the output stream.

I'm guessing that the socket is getting closed AFTER the information is pushed into the output stream, but BEFORE the browser is able to absorb it all.

How do I "wait", in Java, for the other end of a socket to process all the data in the pipe? Or is that even the problem I'm running into? (Note: I've not had this trouble before with the socket programming I've done before. I've got one process where a client connects and I spew tons of data down the pipe with none of this malarky.)

Am I missing something obvious? Yes, I know, I haven't really implemented a web server here, but it should work, shouldn't it?

(Note: (1) I'm just trying to get something to work, (2) I don't have access to any and all libraries on the 'net due to my constricted environment, so I can't just try Jetty, etc.)


The "Server":
Code:
public class Main {

  private static final Logger LOG = Logger.getLogger(Main.class.getName());

  public static void main(String[] args) {
    ServerSocket server = new ServerSocket(8080);
	while(true) {
	  Socket client = server.accept();
	  Thread t = new Thread(new Runnable() {
	    public void run() {
		  try {
		    handleRequest(client);
		  } catch (Exception e) {
		    LOG.log(Level.SEVERE, "", e);
		  }
		}
	  });
	  t.start();
	}
  }
  
  private static void handleRequest(Socket client) throws SQLException, IOException {
     try (Connection conn = DriverManager.getConnection("", "", "") {
	   try (PreparedStatement ps = conn.prepareStatement(P_QUERY)) {
	     try (ResultSet rs = ps.executeQuery()) {
		   JSONArray ja = new JSONArray();
		   while(rs.next()) {
		     Item item = itemFromRs(rs);
			 JSONObject jo = toJsonObject(item);
			 ja.put(jo);
		   }
           String output = ja.toString();
           try (PrintWriter pw = new PrintWriter(client.getOutputStream())) {
		     pw.println("HTTP/1.1 200 OK");
			 pw.println("Access-Control-Allow-Origin: *");
			 pw.println("Content-Type: application/json");  // have tried as text/plain
			 pw.println("Content-Length: " + output.length());
			 pw.println();
			 pw.println(output);
			 pw.println(); // tried with/without this
			 pw.flush();   // tried with/without this
		   }		   
		 }
	   }
	 }
  }

}
 
Okay, so I slurped in the request headers via getInputStream().

My fetch is now working, but now I'm having trouble getting the data out of the promises?

Code:
let d;

async function asdf() {
  fetch("http://localhost:8080').then(function (response) {
    console.log(response);
    response.json().then(function (json) {
      console.log(json);
      return json;
    })
  })
}

function init() {
  d = asdf();

  if (d === undefined) {
    d = // some default test value
  }

  draw();
}

Both console.log statements produce stuff in the log, and it looks correct.

(I'm doing a "select trunc(value,1), count(1) from values group by trunc(value,1) order by trunc(value,1)", so I'm doing a frequency count of all the values in my table using a "bin-size" of 0.1, building the actual JSON objects as ('x', 'y') "tuples")

d always has the default value, never what comes back. After assignment, d is undefined.

Halp? What am I missing and/or not getting/understanding?
 
So, I'm having some weirdness...

I only get data on every other fetch call.

In Firefox, according to the network tab of the browser debugger, it shows the XHR getting created, but nothing tickles my service and , obviously, no data gets back. If I hit refresh, it will work, but I'll get NetworkError in the console log (previous request unfulfilled and the refresh kills it?)

In Chrome, according to the network tab, it shows the request going into (Pending) and never returns. As in Firefox, hitting refresh appears to kill the previous fetch.

These are all "body onLoad()" event-driven. When I added a button to perform the same function, on Firefox, every other request succeeds. On Chrome, every request goes into (Pending) and stays there (seemingly) forever. Again, when these things "fail", I never see any activity on the service side of the fetch.

Has anyone seen this behavior and knows where I screwed up?
 

GohanIYIan

Ars Legatus Legionis
10,191
Maybe add a "Connection: close" header.

HTTP/1.1 connections are persistent by default. If the 2nd (4th, 6th, etc) request is trying to re-use the previous connection you handler's not going to do anything. Refreshing kills the current request and makes the subsequent one open a new connection.

I'm not sure what Chrome's issue would be. Maybe downgrading the response to HTTP/1.0 200 OK would make Chrome more tolerant of a barebones set of response headers.