使用 SocketChannel 實現非阻塞 TCP 客戶端:
public class Client {
public static void main(String[] args) {
try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8088))) {
socketChannel.configureBlocking(false);
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
socketChannel.write(ByteBuffer.wrap("this is client send message".getBytes()));
while (true) {
byteBuffer.clear();
int readBytes = socketChannel.read(byteBuffer);
if (readBytes > 0) {
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, readBytes));
socketChannel.close();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用 ServerSocketChannel 和 Selector 實現多路復用服務端:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.socket().bind(new InetSocketAddress(8088));
serverChannel.configureBlocking(false);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set readyKeys = selector.selectedKeys();
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
System.out.println("accept");
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = ssc.accept();
socketChannel.configureBlocking(false);
int readKeys = socketChannel.read(byteBuffer);
if (readKeys > 0) {
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, readKeys));
}
socketChannel.write(ByteBuffer.wrap("接收到了".getBytes()));
} else if (key.isReadable()) {
System.out.println("read");
} else if (key.isWritable()) {
System.out.println("write");
}
}
}
}
}