Hopefully someone can shed some light on this one, and provide a workaround, or illuminate some method I'm missing here.
Just messing around trying to create a really simple web server.
So far I have:
public class SocketTest {
public static void main(String[] args) throws IOException {
ServerSocket sock = new ServerSocket(9876);
while(true) {
System.out.println("Before");
Socket conn = sock.accept();
System.out.println("After");
conn.close();
}
}
}
Then, once the project is running, the output window displays:
Before
Which is what I expect, but then as soon as I type:
127.0.0.1:9876
Into a web browser, I end up with:
Before
After
Before
After
Before
After
Before
Showing. So the browser is obviously connecting to that port multiple times, but only the first connection contains any info in its page header.
While writing this, I've decided to go a little further with my experimentation's, and come up with:
public class SocketTest {
public static void main(String[] args) throws IOException {
ServerSocket sock = new ServerSocket(9876);
while(true) {
System.out.println("Before");
Socket conn = sock.accept();
System.out.println("After");
Scanner sc = new Scanner(conn.getInputStream());
System.out.println("BEFORE if...");
if (sc.hasNext()) {
System.out.println("INSIDE if...");
String[] cnr = sc.nextLine().split("\\s+");
System.out.println("Command: " + cnr[0] + " - URL: " + cnr[1]);
} else {
System.out.println("INSIDE ELSE!");
}
System.out.println("Closing...");
conn.close();
System.out.println("Closed!");
}
}
}
If you compile and run this code, you'll notice that upon first opening a page on the socket, you get the repeated socket opening, but it also appears to hang for about 10 seconds at the line:
if (sc.hasNext()) {
As though it's watching the InputStream() for a set period of time, to see if it contains any information or not..?
Also, if I send two actual pages in quick succession (or just refresh the page), it goes through immediately.
Can anyone shed some light on this?
Either how I can remove the waiting on an InputStream() that's never going to materialise, or how I can get it to ignore the phantom sockets.
Even a bit of background as to what's causing the anomaly would be great!