客户端
SocketChannel获取到管道 然后转化成非阻塞式的 创建指定缓冲区 并写入数据,吧缓冲区的数据写入到管道中。
服务端
服务端利用ServerSocketChannel获取管道然后也是转换非阻塞绑定 对应的socket的端口然后有对应的选择器以及监听事件的状态,正确的运行版本,代码如下:
客户端
@Test
public void client() throws IOException {
//1.获取通道
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
//2.切换成非阻塞模式
socketChannel.configureBlocking(false);
//3.创建指定缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
Scanner scanner = new Scanner(System.in);
int str = scanner.nextInt();
// while(scanner.hasNext()){
// String str = scanner.next();
buffer.put((LocalDateTime.now().toString() + "\n").getBytes());
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
// }
//4.关闭通道
socketChannel.close();
}
服务端
//服务
public static void main(String[] args) throws IOException {
//1.获取通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2.切换成非阻塞模式
serverSocketChannel.configureBlocking(false);
//3.绑定连接
serverSocketChannel.bind(new InetSocketAddress(9898));
//4.获取选择器
Selector selector = Selector.open();
//5.将通道注册到选择器上,并且指定监听接受事件
//读 SelectionKey.OP_READ 1
//写 SelectionKey.OP_WRITE 4
//连接 SelectionKey.OP_CONNECT 8
//接收 SelectionKey.OP_ACCEPT 16
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//6.轮询式的获取选择器上已经“准备就绪”的事件
while (selector.select() > 0) {
//7.获取当前选择器中的所有注册的“选择键(已就绪的监听事件)”
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
//8.获取准备“就绪”的事件
SelectionKey selectionKey = iterator.next();
//9.判断具体是什么事件准备就绪
if (selectionKey.isAcceptable()) {
//10.若“接收就绪”,获取客户端的连接
SocketChannel socketChannel1 = serverSocketChannel.accept();
//11.切换非阻塞模式
socketChannel1.configureBlocking(false);
//12.将该通道注册到选择器上
socketChannel1.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
//13.获取当前选择器上的"读就绪"状态的通道
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
//14.读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len = 0;
while ((len = socketChannel.read(buffer)) != -1) {
buffer.flip();
System.out.println(new String(buffer.array(),0,len));
buffer.clear();
}
}
//15.取消选择键 selectionKey
iterator.remove();
}
}
}
打印结果
服务端
客户端
错误的版本
客户端 服务端不变
public static void main(String[] args) throws IOException {
//1.获取通道
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
//2.切换成非阻塞模式
socketChannel.configureBlocking(false);
//3.创建指定缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
Scanner scanner = new Scanner(System.in);
==while (scanner.hasNext()) {==
String str = scanner.next();
buffer.put((LocalDateTime.now().toString() + "\n" + str).getBytes());
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
//
// try {
// TimeUnit.SECONDS.sleep(3);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
//4.关闭通道
socketChannel.close();
}
然后
客户端
服务端