简体   繁体   English

在ServerSocket和ServerSocketChannel中接受并绑定

[英]Accept and Bind in ServerSocket and ServerSocketChannel

So I've been going through Sam's Teach Yourself Java in 21 day on the topic of "Communicating Across the Internet". 因此,我在21天的“通过互联网进行交流”主题上经历了Sam的“自学Java”。 Within this dense chapter, one thing it lacks is the relationship between ServerSocketChannel and ServerSocket . 在这个密集的章节中,它缺少的一件事是ServerSocketChannelServerSocket之间的关系。 It's especially perplexing when I read this: 当我读到这篇文章时,它特别令人困惑:

ServerSocketChannel sockChannel = ServerSocketChannel.open();
sockChannel.configureBlocking(false);   

InetSocketAddress server = new InetSocketAddress("localhost", 79);

ServerSocket socket = sockChannel.socket();
socket.bind(server);

...

That ServerSocket object is never used in the rest of the code. ServerSocket对象永远不会在其余代码中使用。

Reading through Java's Documentation, I get that ServerSocketChannel is used for non-blocking purposes when listening for connections while ServerSocket does block. 阅读Java的文档,我得到ServerSocketChannel在ServerSocket阻塞时监听连接时用于非阻塞目的。

  1. So the question is why is the code creating a ServerSocketChannel object (non-blocking) when it's using that to create a ServerSocket object (blocking) to bind to the address? 所以问题是为什么代码在创建ServerSocketChannel对象(非阻塞)时会创建一个ServerSocket对象(阻塞)来绑定到地址?

  2. What would have been the difference if I just used ServerSocketChannel 's bind() instead of ServerSocket 's? 如果我只使用ServerSocketChannelbind()而不是ServerSocket会有什么区别?

The same question applies for the accept() method as well for both classes. 同样的问题也适用于accept()方法以及两个类。

So the question is why is the code creating a ServerSocketChannel object (non-blocking) when it's using that to create a ServerSocket object (blocking) to bind to the address? 所以问题是为什么代码在创建ServerSocketChannel对象(非阻塞)时会创建一个ServerSocket对象(阻塞)来绑定到地址?

I thing your tutorial was written before Java 1.7 was released. 我的教程是在Java 1.7发布之前编写的。 The ServerSocketChannel.bind() was added in java 1.7 release. ServerSocketChannel.bind()是在java 1.7发行版中添加的。 Before that you needed to get the socket to bind the address. 在此之前,您需要让套接字绑定地址。

What would have been the difference if I just used ServerSocketChannel's bind() instead of ServerSocket's? 如果我只使用ServerSocketChannel的bind()而不是ServerSocket,会有什么区别?

Should be no difference. 应该没什么区别。

The same question applies for the accept() method as well for both classes. 同样的问题也适用于accept()方法以及两个类。

Here there is a difference: ServerSocket.accept() always blocks, while ServerSocketChannel.accept() can be configured to not block as you did in the example with sockChannel.configureBlocking(false); 这里有一个区别: ServerSocket.accept()总是阻塞,而ServerSocketChannel.accept()可以配置为不像你在sockChannel.configureBlocking(false);的示例中sockChannel.configureBlocking(false);

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

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