我有一个小的java http服务器:
public class HttpServer {
public static void main(String args[]) {
int port;
ServerSocket server_socket;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
port = 8080;
}
try {
server_socket = new ServerSocket(port, 0, InetAddress.getByName("localhost"));
System.out.println("httpServer running on port "
+ server_socket.getLocalPort()
+ " address " + server_socket.getInetAddress()
);
} catch (IOException e) {
System.out.println(e);
}
}
}
当我使用google chrome连接到localhost时,IDE控制台会写下以下内容:
httpServer running on port 8080 address localhost/127.0.0.1
New connection accepted /127.0.0.1:54839
New connection accepted /127.0.0.1:54840
似乎谷歌Chrome连接两次到服务器,但更改其端口。 为什么会这样?
答案 0 :(得分:0)
由于客户端上的端口8080已被占用,因此客户端的操作系统会将连接映射到客户端上的其他未使用端口。您的客户端从端口54839和54840连接到服务器上的端口80。要允许其他客户端连接到您的服务器,该端口将自动重定向到未使用的端口。
这里列出了发生的事情......
54839和54840是操作系统分配给您尝试连接到本地网站时浏览器创建的两个套接字的端口。
编辑:要正确回答您的问题,您发送浏览器的资源会使其连接两次。一旦检索第一个资源,第二次检索第一个需要的资源。