package nio;
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;
import java.util.Iterator;
/**
* @author: cqh
* @date: 2022/8/14
* @desc:
**/
public class Server {
public static void main(String[] args) {
try {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 9000));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
Iterator iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
int len = 0;
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
while ((len = socketChannel.read(byteBuffer)) > 0) {
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, len));
byteBuffer.clear();
}
}
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
/**
* @author: cqh
* @date: 2022/8/14
* @desc:
**/
public class Client {
public static void main(String[] args) {
try {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9000));
System.out.println(socketChannel.getRemoteAddress());
if (socketChannel.isConnected()) {
System.out.println("连接中");
}
socketChannel.configureBlocking(false);
Scanner scanner = new Scanner(System.in);
String msg = null;
while ((msg = scanner.nextLine()) != null) {
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
伙伴们能帮忙看下,为什么这两段代码不能实现通信效果呢