请举例子
时间: 2023-08-12 13:19:39 浏览: 65
以下是Java Socket异步非阻塞方式读取数据的示例:
```java
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
while (true) {
int readyChannels = selector.select();
if (readyChannels == 0) {
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1) {
// 连接已经关闭
socketChannel.close();
key.cancel();
} else {
// 处理读取到的数据
String data = new String(buffer.array()).trim();
System.out.println("Received data: " + data);
}
}
keyIterator.remove();
}
}
```
这里采用了Java NIO中的Selector和SocketChannel来进行Socket编程,使用异步非阻塞方式读取数据,当连接中断时,不会因为阻塞在输入流上而导致异常。在读取数据时,先判断是否读到了-1,如果读到了则表示连接已经关闭,需要及时关闭Socket和Channel等资源。
阅读全文