java非阻塞io案例
时间: 2024-09-19 18:00:42 浏览: 64
基于Java非阻塞IO技术实现石头剪刀布游戏设计。.zip
Java的非阻塞IO(Non-blocking I/O)通常通过I/O复用技术实现,比如Epoll、Kqueue(Unix系统)或Selector(Java NIO)。这种方式允许线程在等待I/O事件发生时不会阻塞,而是继续执行其他任务。
以下是一个简单的Java NIO非阻塞IO案例:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class NonBlockingServer {
private Selector selector;
private ServerSocketChannel server;
public void start(int port) throws IOException {
server = ServerSocketChannel.open();
server.socket().bind(new InetSocketAddress(port));
selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.selectNow() > 0) {
for (SelectionKey key : selector.selectedKeys()) {
if (key.isAcceptable()) {
accept(key);
} else if (key.isReadable()) {
processRead(key);
}
}
}
}
}
private void accept(SelectionKey key) {
try (SocketChannel client = server.accept()) {
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
} catch (IOException e) {
System.err.println("Error accepting connection: " + e.getMessage());
}
}
private void processRead(SelectionKey key) {
try (SocketChannel channel = (SocketChannel) key.channel()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = channel.read(buffer);
if (read > 0) {
buffer.flip();
// handle the received data here
System.out.println("Received: " + new String(buffer.array()));
buffer.clear(); // reset buffer for next read
} else if (read == -1) { // closed socket
key.cancel();
} else { // error reading
key.close();
}
} catch (IOException e) {
System.err.println("Error reading from client: " + e.getMessage());
}
}
}
阅读全文