简体   繁体   English

在等待连接期间,ServerSocket.accept() 中的线程究竟挂在哪里?

[英]Where exactly does a thread hang in a ServerSocket.accept() during waiting for a connection?

In the block below, I understand that this main thread is blocking and is therefore not listening for interruptions from other threads but does that mean that it literally hangs on the ServerSocket.accept() line?在下面的块中,我知道这个主线程正在阻塞,因此没有监听来自其他线程的中断,但这是否意味着它实际上挂在 ServerSocket.accept() 行上?

        ServerSocket serverSocket = new ServerSocket(8080);

        while(true){ // Block until accept
            Socket acceptedSocket = serverSocket.accept(); // Give accepted socket OR NULL SOCKET to acceptedSocket

            handle(acceptedSocket);

            serverSocket.close();
        }

I am asking because I can't understand where it would be getting hanged up on the accept (ServerSocket.java):我问是因为我不明白它会在哪里挂起接受(ServerSocket.java):

public Socket accept() throws IOException {
        if (isClosed()) // No its open
            throw new SocketException("Socket is closed");
        if (!isBound())   // No its bound to 8080
            throw new SocketException("Socket is not bound yet");
        Socket s = new Socket((SocketImpl) null);                  // Create a null socket
        implAccept(s);                                          // Here???
        return s;
    }

ServerSocket.java again: ServerSocket.java 再次:

protected final void implAccept(Socket s) throws IOException {


  SocketImpl si = null;
    try {
        if (s.impl == null)
          s.setImpl();
        else {
            s.impl.reset();
        }
        si = s.impl;
        s.impl = null;
        si.address = new InetAddress();
        si.fd = new FileDescriptor();
        getImpl().accept(si);    // I'm thinking its here but when I look at this accept, thats an abstract method and don't know where to dig deeper.

Depends on the OS, but on Linux, accept() is a kernel call.取决于操作系统,但在 Linux 上, accept()是 kernel 调用。 The most straighforward Java implementation would be to use that kernel call.最直接的 Java 实现是使用 kernel 调用。

So the process is 'waiting in the kernel', loosely speaking.因此,松散地说,该过程是“在内核中等待”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM