账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    netty 传输文件,
    51
    0

    public class EchoClient {

    public void connect(int port, String host, final String filePath) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        System.out.println("1");
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
    
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                    
                    ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                    ch.pipeline().addLast(new ObjectEncoder());
                    System.out.println("2");
                    ch.pipeline().addLast(new EchoClientHandler(filePath));
                }
            });
            ChannelFuture f = b.connect(host, port).sync();
            System.out.println("4");
            f.channel().closeFuture().sync();
        }     
        finally {
            group.shutdownGracefully();
        }
    }
    @Test
    public  void testClient() {
        int port = 7777;
    
        try {
            //String filePath="E://DSC_4597.JPG";
            //String filePath="G:\\msgShare\\example.jpg";
            String filePath="G:\\msgShare\\boforeInferFile\\example.jpg";
            System.out.println("3");
            new EchoClient().connect(port, "127.0.0.1", filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    }
    下边是
    public class EchoClientHandler extends ChannelHandlerAdapter {

    private static final Logger LOGGER=LoggerFactory.getLogger(EchoClientHandler.class);
    private int dataLength = 1024;
    public RandomAccessFile randomAccessFile;
    private int sumCountpackage = 0;
    private String filePath;
    
    public EchoClientHandler(String filePath) {
        this.filePath=filePath;
    }
    
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(this.filePath);
        try {
            File file=new File(filePath);
            
            randomAccessFile = new RandomAccessFile(file, "r");
            randomAccessFile.seek(0);
    
            if ((randomAccessFile.length() % dataLength) == 0) {
                sumCountpackage = (int) (randomAccessFile.length() / dataLength);
            } else {
                sumCountpackage = (int) (randomAccessFile.length() / dataLength) + 1;
            }
            byte[] bytes = new byte[dataLength];
            
            LOGGER.debug("文件总长度:"+randomAccessFile.length());
            if (randomAccessFile.read(bytes) != -1) {
                EchoFile msgFile = new EchoFile();
                msgFile.setSumCountPackage(sumCountpackage);
                msgFile.setCountPackage(1);
                msgFile.setBytes(bytes);
                msgFile.setFile_md5(file.getName());
                ctx.writeAndFlush(msgFile);
                
    
            } else {
                System.out.println("文件已经读完");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
    
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        if (msg instanceof EchoFile) {
            EchoFile msgEchoFile = (EchoFile) msg;
            int countPackage = msgEchoFile.getCountPackage();
            randomAccessFile.seek(countPackage * dataLength - dataLength);
            int byteLength = 0;
            // 剩余的文件长度
            long remainderFileCount = randomAccessFile.length()
                    - randomAccessFile.getFilePointer();
            
            LOGGER.debug("剩余文件长度:"+remainderFileCount);
            
            if (remainderFileCount < dataLength) {
                LOGGER.debug("小于固定长度:"+remainderFileCount);
                byteLength = (int) remainderFileCount;
    
            } else {
                byteLength = dataLength;
            }
            byte[] bytes = new byte[byteLength];
            if (randomAccessFile.read(bytes) != -1 && remainderFileCount > 0) {
    
                msgEchoFile.setCountPackage(countPackage);
    
                msgEchoFile.setBytes(bytes);
    
                ctx.writeAndFlush(msgEchoFile);
            } else {
                randomAccessFile.close();
                ctx.close();
                System.out.println("文件已经读完--------" + remainderFileCount);
            }
    
        }
    
    }
    
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        try {
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ctx.close();
    }
    
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.debug("服务器断开连接");
        randomAccessFile.close();
    }

    }
    但是 EchoClientHandler中的方法并没有执行
    日志为
    2018-06-26 15:33:06,679-io.netty.util.internal.logging.InternalLoggerFactory-main-DEBUG: Using SLF4J as the default logging framework
    2018-06-26 15:33:06,694-io.netty.channel.MultithreadEventLoopGroup-main-DEBUG: -Dio.netty.eventLoopThreads: 8
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: Platform: Windows
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: -Dio.netty.noUnsafe: false
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: Java version: 8
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: sun.misc.Unsafe.theUnsafe: available
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: sun.misc.Unsafe.copyMemory: available
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: java.nio.Buffer.address: available
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: direct buffer constructor: available
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: java.nio.Bits.unaligned: available, true
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable prior to Java9
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent0-main-DEBUG: java.nio.DirectByteBuffer.<init>(long, int): available
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: sun.misc.Unsafe: available
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: -Dio.netty.tmpdir: C:UsersADMINI~1AppDataLocalTemp (java.io.tmpdir)
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: -Dio.netty.bitMode: 64 (sun.arch.data.model)
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: -Dio.netty.noPreferDirect: false
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: -Dio.netty.maxDirectMemory: 919076864 bytes
    2018-06-26 15:33:06,726-io.netty.util.internal.PlatformDependent-main-DEBUG: -Dio.netty.uninitializedArrayAllocationThreshold: -1
    2018-06-26 15:33:06,726-io.netty.util.internal.CleanerJava6-main-DEBUG: java.nio.ByteBuffer.cleaner(): available
    2018-06-26 15:33:06,741-io.netty.channel.nio.NioEventLoop-main-DEBUG: -Dio.netty.noKeySetOptimization: false
    2018-06-26 15:33:06,741-io.netty.channel.nio.NioEventLoop-main-DEBUG: -Dio.netty.selectorAutoRebuildThreshold: 512
    2018-06-26 15:33:06,757-io.netty.util.internal.PlatformDependent-main-DEBUG: org.jctools-core.MpscChunkedArrayQueue: available
    2018-06-26 15:33:07,084-io.netty.channel.DefaultChannelId-main-DEBUG: -Dio.netty.processId: 9712 (auto-detected)
    2018-06-26 15:33:07,084-io.netty.util.NetUtil-main-DEBUG: -Djava.net.preferIPv4Stack: false
    2018-06-26 15:33:07,084-io.netty.util.NetUtil-main-DEBUG: -Djava.net.preferIPv6Addresses: false
    2018-06-26 15:33:07,195-io.netty.util.NetUtil-main-DEBUG: Loopback interface: lo (Software Loopback Interface 1, 127.0.0.1)
    2018-06-26 15:33:07,195-io.netty.util.NetUtil-main-DEBUG: Failed to get SOMAXCONN from sysctl and file procsysnetcoresomaxconn. Default: 200
    2018-06-26 15:33:07,319-io.netty.channel.DefaultChannelId-main-DEBUG: -Dio.netty.machineId: 3c:97:0e:ff:fe:2e:5d:9d (auto-detected)
    2018-06-26 15:33:07,335-io.netty.util.internal.InternalThreadLocalMap-main-DEBUG: -Dio.netty.threadLocalMap.stringBuilder.initialSize: 1024
    2018-06-26 15:33:07,335-io.netty.util.internal.InternalThreadLocalMap-main-DEBUG: -Dio.netty.threadLocalMap.stringBuilder.maxSize: 4096
    2018-06-26 15:33:07,335-io.netty.util.ResourceLeakDetector-main-DEBUG: -Dio.netty.leakDetection.level: simple
    2018-06-26 15:33:07,335-io.netty.util.ResourceLeakDetector-main-DEBUG: -Dio.netty.leakDetection.targetRecords: 4
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.numHeapArenas: 8
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.numDirectArenas: 8
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.pageSize: 8192
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.maxOrder: 11
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.chunkSize: 16777216
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.tinyCacheSize: 512
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.smallCacheSize: 256
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.normalCacheSize: 64
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.maxCachedBufferCapacity: 32768
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.cacheTrimInterval: 8192
    2018-06-26 15:33:07,366-io.netty.buffer.PooledByteBufAllocator-main-DEBUG: -Dio.netty.allocator.useCacheForAllThreads: true
    2018-06-26 15:33:07,382-io.netty.buffer.ByteBufUtil-main-DEBUG: -Dio.netty.allocator.type: pooled
    2018-06-26 15:33:07,382-io.netty.buffer.ByteBufUtil-main-DEBUG: -Dio.netty.threadLocalDirectBufferSize: 65536
    2018-06-26 15:33:07,382-io.netty.buffer.ByteBufUtil-main-DEBUG: -Dio.netty.maxThreadLocalCharBufferSize: 16384
    2018-06-26 15:33:07,397-org.server.netty.NettyProtoServer-main-DEBUG: 服务端口为:7766

    求解答

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 林朝风 普通会员 1楼

      Netty是一个高性能的开源TCP和UDP套接字服务器和客户端框架。以下是一个简单的示例,展示了如何使用Netty将文件传输到服务器。

      首先,你需要在服务器端实现一个服务器,该服务器可以接收文件上传请求。然后,你需要在客户端实现一个客户端,该客户端可以在指定的文件路径下读取文件内容并将其发送回服务器。

      以下是一个简单的服务器端示例:

      ```java import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.codec.string.StringEncoderUTF8; import io.netty.handler.codec.string.StringDecoderUTF8;

      public class FileServer {

      private final String path;
      private final NioEventLoopGroup bossGroup;
      private final NioEventLoopGroup workerGroup;
      private final String serverName;
      
      public FileServer(String path) {
          this.path = path;
          this.bossGroup = new NioEventLoopGroup();
          this.workerGroup = new NioEventLoopGroup();
          this.serverName = "FileServer-" + System.currentTimeMillis();
      }
      
      public void start() throws Exception {
          serverChannel = new NioServerSocketChannel();
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoder());
          serverChannel.pipeline().addLast(new StringEncoder());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringEncoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new StringDecoderUTF8());
          serverChannel.pipeline().addLast(new String
      
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部