面试题答案
一键面试以下是Java AIO编程中使用AsynchronousServerSocketChannel
绑定到指定端口号的代码示例:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
public class AioServerExample {
public static void main(String[] args) {
try (AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open()) {
// 绑定到指定端口号
serverSocketChannel.bind(new InetSocketAddress(9999));
System.out.println("Server started on port 9999");
// 这里可以开始异步接受客户端连接等操作,为简单示例省略
} catch (IOException e) {
e.printStackTrace();
}
}
}
关键步骤解释:
AsynchronousServerSocketChannel.open()
:- 作用:创建一个新的
AsynchronousServerSocketChannel
实例,用于异步监听新的连接。
- 作用:创建一个新的
serverSocketChannel.bind(new InetSocketAddress(9999))
:- 作用:将
AsynchronousServerSocketChannel
绑定到指定的端口号9999。InetSocketAddress
类用于表示IP地址和端口号的组合,这里构造一个仅指定端口号的实例,IP地址默认为0.0.0.0
(表示接受所有网络接口的连接)。
- 作用:将
System.out.println("Server started on port 9999")
:- 作用:输出服务器已经启动并绑定到指定端口的信息,用于提示和调试。
try - with - resources
块:- 作用:确保
AsynchronousServerSocketChannel
在使用完毕后能够正确关闭,避免资源泄漏。如果在try
块中发生异常,AsynchronousServerSocketChannel
会自动关闭。
- 作用:确保