I wrote a simple java Server programming which just accept a connection and print “Sending response” into screen. When I use safari to connect this server, the server print the result one time, which is a correct result. However, when I reload the page, there will be three “Sending response” to print into the screen. Could anyone can help me?
public class Server {
public void runServer() throws Exception{
ServerSocket socketServer = new ServerSocket(3721);
System.out.println("Listerning for connections on port:"+socketServer.getLocalPort());
while(true){
Socket socket = socketServer.accept();
System.err.println("Established with:"+socket);
String request = parseRequest(socket);
String response = createResponse(request);
sendResponse(response);
socket.close();
}
}
public String parseRequest(Socket socket){
return "request";
}
public String createResponse(String request){
return "response";
}
public void sendResponse(String response){
System.out.println("Sending response");
}
public static void main(String[] args) throws Exception{
Server server = new Server();
server.runServer();
}
}
The outputs are:
Listerning for connections on port:3721
Sending response
Established with:Socket[addr=/0:0:0:0:0:0:0:1%0,port=59055,localport=3721]
Sending response
Established with:Socket[addr=/0:0:0:0:0:0:0:1%0,port=59065,localport=3721]
Established with:Socket[addr=/0:0:0:0:0:0:0:1%0,port=59066,localport=3721]
Sending response
Sending response
Established with:Socket[addr=/0:0:0:0:0:0:0:1%0,port=59067,localport=3721]
When you create the request in Safari to the page, Safari is probably trying to fetch other items in the background, which your servlet is picking up.
One obvious one is the favicon which is displayed next to the URL and for icons in bookmarks.
You should print out what the URI path is in the request to figure out exactly what the requests are. You could use the path to filter out ‘valid’ requests from ‘invalid’ requests.