简体   繁体   English

Netty.io文件传输

[英]Netty.io file transfer

As the title says, I want to transfer specific files from client to server using Netty.io.正如标题所说,我想使用 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.但这从未奏效,因为图像始终是 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 ?).可能是客户端没有发送任何东西(没有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.还要考虑的是,即使您从客户端发送了一个完整的 ByteBuf,这并不意味着由于网络拆分成数据包,在接收方将只有一个 ByteBuf。

Maybe you can have a look at the test example using Chunked handler:也许你可以看看使用 Chunked 处理程序的测试示例:

https://github.com/netty/netty/blob/4.1/handler/src/test/java/io/netty/handler/stream/ChunkedWriteHandlerTest.java 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和 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尝试在管道的两侧添加 LoggingHandler,以查看发生了什么: https://github.com/netty/netty/blob/e83132fcf2f3ee560826586043ed9a87ef2dcfbf/handler/src/main/java/io/netty/handler /logging/LoggingHandler.java#L42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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