简体   繁体   English

ServerSocket.accept()方法的内部实现?

[英]Internal Implementation of ServerSocket.accept() method?

Everyone is aware of socket programming in java. 每个人都知道Java中的套接字编程。 we write a code as below: 我们编写如下代码:

 ServerSocket serverSocket = new ServerSocket(1234);
 Socket server = serverSocket.accept();

We know that we create object of serverSocket and next we write serverSocket.accept(); 我们知道我们创建了serverSocket的对象,接下来我们编写serverSocket.accept(); code to receive client request. 代码以接收客户端请求。 we know that serverSocket.accept(); 我们知道serverSocket.accept(); wait until new request comes. 等到新的请求到来。

but my question is : what serverSocket.accept(); 但我的问题是:什么serverSocket.accept(); method does internally? 方法在内部吗? might be is running in while loop ? 可能正在while循环中运行? how server identify that any new request is came to serve ? 服务器如何识别任何新请求开始服务? what is the internal implmentation of serverSocket.accept(); serverSocket.accept();的内部实现是什么serverSocket.accept(); method? 方法? Any One has idea about this? 有人对此有想法吗?

On Linux, the ServerSocket.accept() ultimately (in native code) does an accept syscall (see man 2 accept ) which blocks waiting for a suitable incoming connection. 在Linux上, ServerSocket.accept()最终(以本机代码形式)执行accept系统调用(请参阅man 2 accept ),该调用阻止等待适当的传入连接。

There is no while loop in the Java code or in the native code. Java代码或本机代码中没有while循环。 I've no idea what happens inside the Linux kernel, but at that point this is no longer a Java question. 我不知道Linux内核内部会发生什么,但是到那时,这不再是Java问题。


The same would probably apply for Java on Windows, and for C# or any other programming language that you cared to consider. Windows上的Java,C#或您考虑考虑的任何其他编程语言也可能适用同样的方法。

You can find this by your own. 您可以自己找到它。

public Socket accept() throws IOException {
    if (isClosed())
        throw new SocketException("Socket is closed");
    if (!isBound())
        throw new SocketException("Socket is not bound yet");
    Socket s = new Socket((SocketImpl) null);
    implAccept(s);
    return s;
}

How accept() works? accept()如何工作?

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

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