简体   繁体   中英

Netty.io file transfer

As the title says, I want to transfer specific files from client to server using Netty.io. I've tried sending bytes from the client to the server, putting those bytes into an array and then create a file off of them but it did not work. This is the code:

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws IOException {
    byte[] bytes = new byte[buf.readableBytes()];
    buf.readBytes(bytes);
    InputStream in = new ByteArrayInputStream(bytes);
    BufferedImage image = ImageIO.read(in);
    System.out.println(image);
    try{
        ImageIO.write(image, "jpg", new File("ok.jpg"));
    }catch (Exception ignored){}

That never worked though, as image would always be null. I've pretty much tried everything I could find but it's either an outdated code / explanation or bad answers.

So, how would I be able to send a file from the client to the server?

The client side is not given in your example, so difficult to find out the reason. It might be that the client is not sending anything (no flush ?). Also consider that even if you send a full ByteBuf from client side, it does not mean that on receiver side there will be only one ByteBuf due to network splitting into packets.

Maybe you can have a look at the test example using Chunked handler:

https://github.com/netty/netty/blob/4.1/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java

and the API: https://netty.io/4.1/api/io/netty/handler/stream/package-summary.html

Try to add the LoggingHandler in your pipeline on both sides, in order to see what is going on: https://github.com/netty/netty/blob/e83132fcf2f3ee560826586043ed9a87ef2dcfbf/handler/src/main/java/io/netty/handler/logging/LoggingHandler.java#L42

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM