首页 > 代码库 > 【Java nio】Blocking nio2

【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();
    }
}

 

【Java nio】Blocking nio2