我正在阅读 Java 中的 TCP/IP 套接字,关于服务器套接字,它说
When we call accept() on that ServerSocket instance, if a new connection is pending, accept() returns immediately; otherwise it blocks until either a connection comes in or the timer expires, whichever comes first. This allows a single thread to handle multiple connections. Unfortunately, the approach requires that we constantly poll all sources of I/O, and that kind of “busy waiting” approach again introduces a lot of overhead from cycling through connections just to find out that they have nothing to do.
据我了解,当连接到来时是否应该“通知”,因此不应该“忙等待”?我是不是误会了什么……?
-----------------编辑----------------------
全文如下:
Because of these complications, some programmers prefer to stick with a single-threaded approach, in which the server has only one thread, which deals with all clients—not sequentially, but all at once. Such a server cannot afford to block on an I/O operation with any one client, and must use nonblocking I/O exclusively. Recall that with nonblocking I/O, we specify the maximum amount of time that a call to an I/O method may block (including zero). We saw an example of this in Chapter 4, where we set a timeout on the accept operation (via the setSoTimeout() method of ServerSocket). When we call accept() on that ServerSocket instance, if a new connection is pending, accept() returns immediately; otherwise it blocks until either a connection comes in or the timer expires, whichever comes first. This allows a single thread to handle multiple connections. Unfortunately, the approach requires that we constantly poll all sources of I/O, and that kind of “busy waiting” approach again introduces a lot of overhead from cycling through connections just to find out that they have nothing to do
最佳答案
即使在整个引文中,这也大多是无稽之谈。 或者您正在使用阻塞 I/O,在这种情况下,您需要每个连接一个线程,并且每个 receive() 循环需要另一个线程,或者您正在使用非阻塞 I/O,在这种情况下,您可以使用 Java 7 中的 select(),或者,您正在使用异步 I/O,在这种情况下,所有回调都是完成处理程序。在这些情况下,您都不需要轮询或忙等待。
我认为他一定是指使用具有非常短的超时时间的阻塞模式,但这确实是最不清楚的。
关于java - 关于Java ServerSocket接受: busy-wating?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419813/