user2884473
user2884473

Reputation: 1

Java socket programming, why browser established connection more than one time?

import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.net.*;
import java.util.concurrent.*;

public class Server {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(80);
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Test");
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

When I use chrome to visit localhost:80, why does the server print the string "Test" 3 times? And it print twice when I use IE10 to visit it.

Upvotes: 0

Views: 212

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533492

When it connects to a web server it asks for a number resources like the favicon. I suggest you print what it is asking for so you don't have guess why it is accessed more than once.

Upvotes: 3

If you printed out the HTTP request it's making, you'd probably see why. Most likely, the browser is either attempting to load favicon.ico for your "site" (localhost), or it's trying to reconnect to a server that's not speaking correct HTTP.

Upvotes: 3

Related Questions