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();
        }
    }
  • 相关阅读:
    Qt中QString,int,char,QByteArray之间相互转换
    Qt中的多线程编程
    在Qt中使用sleep(包含为win and *nix下sleep函数的实现及用法)
    Qt Creator 快捷键
    基于FFmpeg和Qt的播放器 QtAV库
    Ubuntu下APACHE HTTPS安装和配置
    很受欢迎的Linux笔记(短小精悍)
    QT基本使用
    FLV封装格式及分析器工具
    AVPicture、AVFrame和AVPacket
  • 原文地址:https://www.cnblogs.com/dream-to-pku/p/6505537.html
Copyright © 2011-2022 走看看