I am learning the book how tomcat works and find a thing which make me a big surprise. I simplify the code as below:
public class Boot {
public static void main(String[] args) {
ServerDemo server = new ServerDemo();
try {
server.start();
System.in.read();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerDemo implements Runnable {
private ServerSocket serverSocket = null;
public void run() {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
System.out.println("--receive request from client----"+
Thread.currentThread().getId());
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void start() {
try {
serverSocket = new ServerSocket(8080);
Thread thread = new Thread(this);
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
the Boot
class is Main class and used to boot this application and the ServerDemo
class is a simplified server which listen 8080 port and will print info when a request from browser reach.
Now the question is that: I think when I make a request from browser it will execute
socket = serverSocket.accept();
and then print info only once and then thread block itself because of accept method
waiting the next request.
But the real is that the thread print info several times:(maybe 3,4..) about a request.
and this is a executing: input:
http://localhost:8080/index
output:
--receive request from client----13
--receive request from client----13
--receive request from client----13
my expected output:
--receive request from client----number
summary: I cant figure out about one request why it prints several times it means accept method execute several times.
Its probably your browser trying a few different things to get you to response cause you just closed the connection on them. Try using
curl
orwget
instead. – ug_