码迷,mamicode.com
首页 > 其他好文 > 详细

9、NIO--阻塞式

时间:2019-05-09 00:36:31      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:sock   channel   客户端连接   exce   test   bin   and   pat   read   

 

使用NIO完成网络通信的三个核心:

1、通道(Channel):负责连接

  java.nio.channels.Channel接口:

    SelectableChannel抽象类:有一下几个实现类

      SocketChannel      TCP

      ServerSocketChannel  TCP

      DategramChannel      UDP

      Pipe.SinkChannel

      Pipe.SourceChannel

 

 

2、缓冲区(Buffer):负责数据的存取

3、选择器(Selector):式SelectableChannel的多路复用器,用于监控SelectableChannel的IO状况

 

 

 

代码实例:

    //服务端
    @Test
    public void server() throws IOException{
        
        //1、获取异常
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        
        //2、绑定连接
        serverSocketChannel.bind(new InetSocketAddress(8081));
    
        //3、获取客户端连接的通道
        SocketChannel sockChannel = serverSocketChannel.accept();
        
        //4、分配指定大小的缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        
        //5、接收客户端的数据保存到本地
        FileChannel outChannel = FileChannel.open(Paths.get("d:\\aaa.jpg"), StandardOpenOption.WRITE
                            ,StandardOpenOption.CREATE,StandardOpenOption.READ);
        
        while(sockChannel.read(buf) != -1){
            buf.flip();
            outChannel.write(buf);
            buf.clear();
        }
        
        serverSocketChannel.close();
        outChannel.close();
        sockChannel.close(); 
    }

 

 

    //客户端
    @Test
    public void client(){
        
        //1、获取通道
        SocketChannel socketChannel = null;
        
        FileChannel inChannel = null;
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8081));
            
            //2、分配指定大小的缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);
            
            //3、读取本地文件,并且发送
            inChannel = FileChannel.open(Paths.get("d:\\a.jpg"), StandardOpenOption.READ);
            
            while(inChannel.read(buf) != -1){
                buf.flip();
                socketChannel.write(buf);
                buf.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    inChannel.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }

 

先开启服务端在开启客户端:

技术图片

 

9、NIO--阻塞式

标签:sock   channel   客户端连接   exce   test   bin   and   pat   read   

原文地址:https://www.cnblogs.com/Mrchengs/p/10836011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!