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();
            }
        }
        
    尽早把自己的生活折腾成自己想要的样子
  • 相关阅读:
    SpringSource Tools Suite 字体偏小问题
    Ubuntu11.10 Eclipse 提示框 为黑色 解决方案
    图的广度优先搜索 皇星客栈
    哈夫曼编码 皇星客栈
    m_hWnd与this指针 皇星客栈
    建立中序线索二叉树 皇星客栈
    第一部分 整数Hash 皇星客栈
    哈夫曼树建立 皇星客栈
    Hash入门 皇星客栈
    stdin,stdout 和STDOUT_FILENO,STDIN_FILENO的学习 皇星客栈
  • 原文地址:https://www.cnblogs.com/v-lcc/p/9704746.html
Copyright © 2011-2022 走看看