Netty没有写 [英] Netty doesn't write

查看:363
本文介绍了Netty没有写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试使用netty写入时,写入的数据永远不会在远程端结束,用Wireshark确认。

When trying to write with netty, the written data never ends up at the remote side, confirmed with Wireshark.

我试过:

//Directly using writeAndFlush
channel.writeAndFlush(new Packet());

//Manually flushing
channel.write(new Packet());
channel.flush();

// Even sending bytes won't work:
channel.writeAndFlush(new byte[]{1,2,3});

当我将其包装在中时,没有异常被捕获{...} catch(Throwable e){e.printStackTrace();}

我可以做些什么来调试这个问题?

What can I do to debug this problem?

推荐答案

Netty是异步的,这意味着当写入失败时它不会抛出异常。它会返回一个 Future<?> ,而不是抛出异常,它将在请求完成时更新。确保记录来自此的任何异常作为您的第一个调试步骤:

Netty is an asynchronous, meaning that it won't throw exceptions when a write failed. Instead of throwing exceptions, it returns a Future<?> that will be updated when the request is done. Make sure to log any exceptions coming from this as your first debugging steps:

channel.writeAndFlush(...).addListener(new GenericFutureListener<Future<Object>>() {
    @Override
    public void operationComplete(Future<Object> future) {
        // TODO: Use proper logger in production here
        if (future.isSuccess()) {
            System.out.println("Data written succesfully");
        } else {
            System.out.println("Data failed to write:");
            future.cause().printStackTrace();
        }
    }
});

或更简单:

channel.writeAndFlush(...).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);

在得到异常的根本原因后,可能会出现多个问题:

After you get the root cause of the exception, there could be multiple problems:

注意:使用 ObjectEncoder ,但您的对象未实现 Serializable

默认的Netty频道只能发送 ByteBuf s和 FileRegion s。您需要通过向管道添加更多处理程序或将其手动转换为 ByteBuf s将对象转换为这些类型。

A default Netty channel can only send ByteBufs and FileRegions. You need to convert your objects to these types either by adding more handlers to the pipeline, or converting them manually to ByteBufs.

A ByteBuf 是字节数组的Netty变体,但具有性能潜力,因为它可以存储在直接存储空间中。

A ByteBuf is the Netty variant of a byte array, but has the potential for performance because it can be stored in the direct memory space.

通常使用以下处理程序:

The following handlers are commonly used:


转换 String 使用 StringEncoder
转换 Serializable 使用 ObjectEncoder (警告,与普通Java对象流不兼容)
转换 byte [] 使用 ByteArrayEncoder

To convert a String use a StringEncoder To convert a Serializable use a ObjectEncoder (warning, not compatible with normal Java object streams) To convert a byte[] use a ByteArrayEncoder

注意:由于TCP是基于流的协议,通常需要附加某种形式的数据包大小,因为您可能无法收到您编写的确切数据包。请参阅处理基于流的传输在Netty wiki中获取更多信息。

Notice: Since TCP is a stream based protocol, you usually want some form of packet sizes attached, since you may not receive exact packets that you write. See Dealing with a Stream-based Transport in the Netty wiki for more information.

这篇关于Netty没有写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆