Java NIO(三)通道Channel

一、使用RandomAccessFile.getChannel()实现文件复制

    public void fileCopy() throws IOException{
        RandomAccessFile source = new RandomAccessFile("D:" + File.separator + "x.txt", "r");
        RandomAccessFile dest = new RandomAccessFile("D:" + File.separator + "y.txt", "rw");
        FileChannel srcChannel = source.getChannel();
        FileChannel destChannel = dest.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        while(srcChannel.read(byteBuffer) != -1){
            //切换到写入模式
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()){
                destChannel.write(byteBuffer);
            }
            byteBuffer.clear();
        }
        srcChannel.close();
        destChannel.close();
    }

 

二、信息传输

1.传统IO流信息传输

服务端

public class SimpleServerSocket {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(1234));
            Socket socket = serverSocket.accept();
            System.out.println("accept connection from:" + socket.getRemoteSocketAddress());
            InputStream is = socket.getInputStream();
            byte[] bytes = new byte[1024];
            while (is.read(bytes) != -1) {
                String str = new String(bytes);
                if (str.equals("exit")) {
                    break;
                }
                System.out.println(str);
                bytes = new byte[1024];
            }
            is.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端

public class SimpleClientSocket {
    public static void main(String[] args) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress("127.0.0.1", 1234));
            OutputStream os = socket.getOutputStream();
            os.write("hello".getBytes());
            Thread.sleep(100);
            os.write("world".getBytes());
            Thread.sleep(100);
            os.write("exit".getBytes());
            os.close();
            socket.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.阻塞式通道信息传输

服务端

public class BlockingServerChannel {
    public static void main(String[] args) {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(1234));
            SocketChannel sc = ssc.accept();
            System.out.println("accept connection from:" + sc.getRemoteAddress());
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (sc.read(buffer) != -1) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println(new String (bytes));
                buffer.clear();
            }
            sc.close();
            ssc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端

public class BlockingClientChannel {
    public static void main(String[] args) {
        try {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("127.0.0.1", 1234));
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            writeString(buffer, sc,"hello");
            Thread.sleep(100);
            writeString(buffer, sc,"world");
            Thread.sleep(100);
            writeString(buffer, sc,"exit");
            sc.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void writeString(ByteBuffer buffer, SocketChannel sc,String str) {
        buffer.clear();
        buffer.put(str.getBytes()).flip();
        try {
            sc.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.非阻塞式信息传输

服务端

public class NonBlockingServerChannel {
    public static void main(String[] args) {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open( );
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(1234));
            SocketChannel sc;
            while ((sc = ssc.accept()) == null) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("try to accept again...");
            }
            System.out.println("accept connection from:" + sc.getRemoteAddress());

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (sc.read(buffer) != -1) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println(new String (bytes));
                buffer.clear();
            }
            sc.close();
            ssc.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

客户端

public class NonBlockingClientChannel {
    public static void main(String[] args) {
        try {
            SocketChannel sc = SocketChannel.open();
            sc.configureBlocking(false);
            sc.connect(new InetSocketAddress("127.0.0.1", 1234));
            while (!sc.finishConnect()) {
                System.out.println("connection has not finished,wait...");
                TimeUnit.SECONDS.sleep(1);
            }
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            writeString(buffer, sc,"hello");
            Thread.sleep(100);
            writeString(buffer, sc,"world");
            Thread.sleep(100);
            writeString(buffer, sc,"exit");
            sc.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    private static void writeString(ByteBuffer buffer, SocketChannel sc,String str) {
        buffer.clear();
        buffer.put(str.getBytes()).flip();
        try {
            sc.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

参考文章:

Java NIO编程实例之二Channel

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值