车传新 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();
    }
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办