4.案例

服务端:
package cn.tedu.nio.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo01 {
    public static void main(String[] args) throws Exception {
        //1.创建ServerSockentChannel对象
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //2.绑定指定端口
        ssc.bind(new InetSocketAddress(44444));
        //3.设置非阻塞模式
        ssc.configureBlocking(false);
        //4.接收客户端连接
        SocketChannel sc = null;
        while(sc == null){
            sc = ssc.accept();
        }
        sc.configureBlocking(false);
        //5.读取数据
        ByteBuffer buf = ByteBuffer.allocate(5);
        while(buf.hasRemaining()){
            sc.read(buf);
        }
        //6.获取数据打印
        byte[] arr = buf.array();
        String str = new String(arr);
        System.out.println(str);
        
        //5.关闭通道
        sc.close();
        ssc.close();
    }
}

客户端:
    package cn.tedu.nio.channel;
    
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SocketChannel;
    
    public class SocketChannelDemo01 {
        public static void main(String[] args) throws Exception {
            //1.创建客户端SocketChannel
            SocketChannel sc = SocketChannel.open();
            //2.配置启用非阻塞模式
            sc.configureBlocking(false);
            //3.连接服务器
            boolean isConn = sc.connect(new InetSocketAddress("127.0.0.1", 44444));
            if(!isConn){
                while(!sc.finishConnect()){
                }
            }
            
            //4.发送数据到服务器
            ByteBuffer buf = ByteBuffer.wrap("abcde".getBytes());
            while(buf.hasRemaining()){
                sc.write(buf);
            }
            
            //5.关闭通道
            sc.close();
        }
    }
    
尽早把自己的生活折腾成自己想要的样子
原文地址:https://www.cnblogs.com/v-lcc/p/9704746.html