zoukankan      html  css  js  c++  java
  • 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();
            }
        }
        
    尽早把自己的生活折腾成自己想要的样子
  • 相关阅读:
    机器学习-Matplotlib绘图(柱状图,曲线图,点图)
    人工智能-机器学习之numpy方法
    爬虫解码~以及我的一些小经验
    django-子项目
    Django-模板语法
    Django-cookie的保存以及删除操作
    django-路由
    响应式瀑布流
    原生js实现最简单的瀑布流布局
    原生js用div实现简单的轮播图
  • 原文地址:https://www.cnblogs.com/v-lcc/p/9704746.html
Copyright © 2011-2022 走看看