zoukankan      html  css  js  c++  java
  • 【Java nio】Blocking nio2

    package com.slp.nio;
    
    import org.junit.Test;
    
    import java.io.File;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    
    /**
     * Created by sanglp on 2017/3/1.
     */
    public class TestBlockingNIO2 {
        //客户端
        @org.junit.Test
        public void client() throws IOException {
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
            FileChannel fileChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (fileChannel.read(buffer)!=-1){
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
            }
    
            socketChannel.shutdownOutput();//不加这个会一直处于阻塞状态
            //接受服务器反馈
            int len=0;
            while (socketChannel.read(buffer)!=-1){
                System.out.println(new String(buffer.array(),0,len));
                buffer.clear();
            }
            fileChannel.close();
            socketChannel.close();
    
        }
        //服务端
        @Test
        public void server() throws IOException {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
            serverSocketChannel.bind(new InetSocketAddress(9898));
    
            SocketChannel socketChannel = serverSocketChannel.accept();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(buffer)!=-1){
              buffer.flip();
                outChannel.write(buffer);
                buffer.clear();
            }
    
            //发送反馈
            buffer.put("服务器数据接收成功".getBytes());
            buffer.flip();
            socketChannel.write(buffer);
            socketChannel.close();
            serverSocketChannel.close();
        }
    }
  • 相关阅读:
    屏幕录像大师2016【破解版】
    Hibernate demo之使用注解
    Hibernate demo之使用xml
    Hibernate 的<generator class="native"></generator>的不同属性含义
    java 动态实现接口
    c# emit 实现类的代理
    c# emit 动态实现接口
    java nio读取和写入文件
    java 读取Properties
    Java中利用MessageFormat对象实现类似C# string.Format方法格式化
  • 原文地址:https://www.cnblogs.com/dream-to-pku/p/6505537.html
Copyright © 2011-2022 走看看