netty 传输文件,

发布于 2022-09-07 15:39:29 字数 10331 浏览 9 评论 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

求解答

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溇涏 2022-09-14 15:39:30

问题解决了吗?什么情况?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文