车传新 2018-12-17 02:21 采纳率: 0%
浏览 1720

netty如何实现阻塞IO?

项目需求需要在服务端实现一个阻塞IO,即netty发送完数据之后需要阻塞线程,直到有数据返回

  • 写回答

1条回答

  • weixin_43547591 2018-12-20 05:10
    关注

    @Test
    public void client(){
    try {
    //1.获取通道
    SocketChannel clientChannel = SocketChannel.open(
    new InetSocketAddress("127.0.0.1", 7979));
    System.out.println("client is start connecting...");
    FileChannel fileChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
    //2.分配指定大小的缓冲区
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //3.读取本地文件,并向服务端发送文件
    while(fileChannel.read(buffer)!=-1){
    buffer.flip();
    clientChannel.write(buffer);
    buffer.clear();
    }
    clientChannel.shutdownOutput();//告诉服务端数据已经发送完毕,否则客户端和服务端都会处于阻塞状态
    //4.接收服务端的反馈
    int len = 0;
    while((len = clientChannel.read(buffer))!=-1){
    buffer.flip();
    System.out.println(new String(buffer.array(),0,len));
    buffer.clear();
    }
    //5.关闭通道
    clientChannel.close();
    fileChannel.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    @Test
    public void server(){
    try {
    //1.获取通道
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    FileChannel outChannel = FileChannel.open(
    Paths.get("bio.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
    //2.绑定端口
    serverChannel.bind(new InetSocketAddress(7979));
    System.out.println("Server start in port:7979...");
    //3.获取客户端连接
    SocketChannel socketChannel = serverChannel.accept();
    //4分配指定到小的缓冲区
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    //5.读取数据
    while (socketChannel.read(byteBuffer)!=-1){
    byteBuffer.flip();
    outChannel.write(byteBuffer);
    byteBuffer.clear();
    }
    //6.发送反馈给客户端
    byteBuffer.put("服务端接收数据成功!".getBytes());
    byteBuffer.flip();
    socketChannel.write(byteBuffer);
    //7.关闭通道
    socketChannel.close();
    outChannel.close();
    serverChannel.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!