简体   繁体   English

Java Netty-根据输入消息将结果作为StringEncoder或ObjectEncoder发送到客户端吗?

[英]Java Netty - Send result to client as StringEncoder or ObjectEncoder depending on input message?

I'm new to Netty and so far there is a working client-server which can handle String message with StringEncoder and StringDecoder, eg: 我是Netty的新手,到目前为止,有一个工作的客户端服务器可以使用StringEncoder和StringDecoder处理String消息,例如:

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                       .channel(NioServerSocketChannel.class)
                       .handler(new LoggingHandler(LogLevel.TRACE))
                       .childHandler(new ChannelInitializer<SocketChannel>() {
                                            @Override
                                            public void initChannel(SocketChannel ch) throws Exception {
                                                ch.pipeline().addLast(
                                                    new LoggingHandler(LogLevel.TRACE),
                                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                                    new StringEncoder(),
                                                    new StringDecoder(),
                                                    new ReceiveMessageCommunicatorHandler(localNode, inpeerNodeRegistry, outpeerNodeRegistry));

The input message is just like this: excute_this and server sends back: ok . 输入消息如下: excute_this ,服务器发送回: ok

Now, what I need to do is a server receives a new text message: get_object , it should send back to any client (eg: telnet or java application which uses the plain socket) a serialized object as byte array. 现在,我需要做的是服务器收到一条新的文本消息: get_object ,它应该将序列化的对象作为字节数组发送回任何客户端(例如:使用普通套接字的telnet或java应用程序)。 Then in this client, it can deserialized this object as Java object. 然后,在此客户端中,可以将该对象反序列化为Java对象。

I've known that ObjectEncoder() seems to be the way to do. 我知道ObjectEncoder()似乎是这样做的方法。 But, it also serializes the response which should be String to a serialized object while it should do it for some specific messages (eg: get_object only). 但是,它还会将应为String的响应序列化为序列化的对象,而对某些特定消息则应这样做(例如: 仅限于get_object )。

How can I tell Netty when it should encode result as StringEncoder and when should encode as Serialized Object as byte array? 我该如何告诉Netty何时应将结果编码为StringEncoder,何时应将序列化对象编码为字节数组?

It is possible to dynamically modify the pipeline. 可以动态修改管道。 When you receive get_object message you can simply remove the StringEncoder and add the ObjectEncoder in the relevant ChannelInboundHandler 收到get_object消息时,您只需删除StringEncoder并将ObjectEncoder添加到相关的ChannelInboundHandler

   ChannelPipeline p = ctx.pipeline();
    if (p.get(StringEncoder.class) != null) {
        p.remove(StringEncoder.class);
    }
    p.addLast(new YourObjectEncoder())

Or if you know the name of your encoder you can do a replace: 或者,如果您知道编码器的名称,则可以进行替换:

p.replace("encoder", "encoder", new YourObjectEncoder());

Thanks for suggestion of Riyafa Abdul Hameed 感谢您对Riyafa Abdul Hameed的建议

It can switch Encoder dynamically as in this code when server received a message and writes response to client. 当服务器接收到一条消息并将响应写入客户端时,它可以按此代码动态切换编码器。

@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
    InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
    MessageContainer messageContainer = new MessageContainer(message, address);
    log.debug("\n");
    log.debug("Message received: {}", message);

    // Handle received message and write result back to the sender
    Object response = this.handleMessage(messageContainer);
    if (response instanceof String) {
        ctx.channel().pipeline().names();
        ctx.channel().pipeline().remove(ObjectEncoder.class);
        ctx.channel().pipeline().addFirst(new StringEncoder());
    }

    if (response != null) {
        ctx.write(response);
        ctx.flush();
    }
    ctx.close();
}

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

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