面试题答案
一键面试import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class AsynchronousSocketChannelExample {
public static void main(String[] args) {
try (AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open()) {
InetSocketAddress address = new InetSocketAddress("remote-server-host", 12345);
Future<Void> future = socketChannel.connect(address);
while (!future.isDone()) {
// 可以在这里做其他事情,而不是阻塞等待
}
try {
future.get();
System.out.println("Connected to server.");
// 处理数据发送和接收
ByteBuffer buffer = ByteBuffer.wrap("Hello, Server!".getBytes());
socketChannel.write(buffer).get();
buffer.clear();
socketChannel.read(buffer).get();
buffer.flip();
System.out.println("Received from server: " + new String(buffer.array(), 0, buffer.limit()));
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码使用AsynchronousSocketChannel
尝试连接到远程服务器,并处理连接过程中的异常。具体步骤如下:
- 打开通道:通过
AsynchronousSocketChannel.open()
方法打开一个异步套接字通道。 - 连接服务器:创建一个
InetSocketAddress
对象指定远程服务器的地址和端口,然后调用connect
方法发起连接,该方法返回一个Future<Void>
对象。通过检查Future
的完成状态来判断连接是否成功。 - 处理连接结果:在获取连接结果时捕获
InterruptedException
和ExecutionException
异常,以处理连接过程中可能出现的中断和执行异常。 - 数据交互:连接成功后,通过
write
和read
方法进行数据的发送和接收,并处理可能出现的异常。在实际应用中,还需要考虑更多的异常情况和错误处理逻辑,如连接超时、服务器拒绝连接等。
注意:请将"remote-server-host"
替换为实际的远程服务器主机名或IP地址,12345
替换为实际的端口号。