为什么ChannelHandlerContext.writeAndFlush()不处理我的字符串?

时间:2018-03-21 01:54:06

标签: java netty

我使用Netty 4.1.16创建服务器。我建立了一个管道:

socketChannel.pipeline()
        //Line Based Frame Decoder will split a message into frames separated by CR/LF.
        // This one discards the delimiter and fails on excessive length only when the
        // entire frame has been read.
        .addLast("Frame Decoder", new LineBasedFrameDecoder(MAX_FRAME_LENGTH, true, false))
        // String decoder changes inbound byte stream into a string.
        .addLast("String Decoder", new StringDecoder(CharsetUtil.US_ASCII))
        // VoiceMessage is a custom decoder that turns a string into a socket message
        // and passes it to a command handler thread.
        .addLast("VoiceMessage Decoder", new InboundVoiceHandler())
        // String encoder allows us to write a string directly to the channel without needing
        // to write a custom string-to-byte encoder.
        .addLast("String Encoder", new StringEncoder(CharsetUtil.US_ASCII));

稍后在我的代码中,我创建了一个对传入消息的String响应,并尝试使用它将其写入ChannelHandlerContext:

    message = pack.getBoardList() == null || pack.getBoardList().size() > 0
            ? "Existing pack number " + pack.getPackNo() + " has been recalled."
            : "New pack number " + pack.getPackNo() + " has been started.";
    new OutboundTalkmanMessage(channelHandlerContext, voiceMessage.getVoiceSession())
            .writeAndFlush(message, vdtsSysDB);

...

public class OutboundTalkmanMessage {
    private VoiceSession voiceSession;
    private ChannelHandlerContext ctx;

    private static final Logger LOG = LoggerFactory.getLogger(OutboundTalkmanMessage.class);

    public OutboundTalkmanMessage(ChannelHandlerContext ctx, VoiceSession voiceSession) {
        this.ctx = ctx;
        this.voiceSession = voiceSession;
    }

    public void writeAndFlush(String message, VdtsSysDB vdtsSysDB) {
        saveOutgoingMessage(message, vdtsSysDB);
        String talkmanMessage = "\"" + message + "\"\r\n\n";
        LOG.info("Ougoing message: [{}]", talkmanMessage);
        try {
            ChannelFuture channelFuture = ctx.writeAndFlush(talkmanMessage);
            LOG.info("Waiting for write.");
            channelFuture.addListener(future -> {
                if (future.isSuccess()) LOG.info("Write succeeded.");
                else {
                    LOG.error("Write failed. {}", future.cause());
                }
                LOG.info("Message sent.");
                ctx.close();
            });
        } catch (Exception e) {
            LOG.error("Error writing talkman output.", e);
        }
    }
}

My ChannelHandlerContext.writeAndFlush(String msg)失败,原因是

java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion)

正如我理解文档和示例一样,writeAndFlush应该将一个字符串写入管道,字符串编码器应该将该字符串更改为bytebuf,然后再将其转发给套接字进行传输。 我检查了通道管道,StringEncoder肯定在那里注册了。我尝试过通过Netty库的执行路径,但这种方式很疯狂。 我使用了错误的写电话吗? writeAndFlush是否正在跳过StringEncoder?我应该放弃编程并重新回到我的工作中作为碰撞测试假人吗?

1 个答案:

答案 0 :(得分:1)

我认为你想使用Channel.writeAndFlush来确保你走完整个ChannelPipeline。您最有可能使用位于ChannelHandlerContext之前的ChannelHandler StringEncoder,因此不会对其进行处理。