Yes, it is an interesting issue. I'm not much into sockets and all, but out of curiosity, I tried to run the code and faced the same issue.
And I would really like to know why this happens
Meanwhile, I tried to put a counter as part of message (and the counter is increased during each iteration), and below is what I got:
1) When I run the code on a new port (e.g. 5555), then for first time, I get this message 3 times. The last counter on console is 3, however, the counter on browser (which we write via PrintWriter) is 1.
2) If I refresh browser page (i.e. send request again), then counter is 4 on both - console and browser. After this, it remains in sync (on console and browser).
3) I checked after inserting print statements and found that the loop is actually executing multiple times. The only reason I can think of is due to the way browser sends the request, accept method is being invoked more than once (but then, I'm still not sure why we do not get last counter's value '3' on browser).
4) Once those counter values are in sync (i.e. after first refresh), this problem never occurs with that particular port (I also tried restarting the program, in which case, the values were in sync right from counter = 1). To reproduce the problem on the same port, I had to restart the machine.
I hope someone knowledgeable in this might find above analysis helpful.
You're assuming that a single high-level browser activity results in a single connection to your socket. I would say the fact that you're seeing the output multiple times is evidence that that assumption is incorrect. Java code doesn't just execute on its own for no reason. Maybe the browser retries since it didn't get a valid HTTP response. Maybe there's something else unexpected going on in the browser. Whatever the case, if you're seeing that output 3 times, there are definitely 3 connections being made.
However, I'm still not getting why there's inconsistency in browser and console data during first request.
When I tried to add counter's value to the message, browser displayed the value as 1 (which means that browser was able to establish the connection in first attempt, and also read the response). So, why there were extra attempts for connection?
Also, for same socket, why this behaviour never happens again (unless I bounce the machine)?
Surprisingly, it works totally fine when I connect to ServerSocket via other Java code instead of browser.