如何将ObjectDecoder添加到Netty服务器

图菲尔

服务器代码来自netty QOTM(当下报价)示例

package net.bounceme.dur.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import java.util.logging.Logger;

public final class Server {

    private static final Logger log = Logger.getLogger(Server.class.getName());

    public static void main(String[] args) throws InterruptedException {
        MyProps p = new MyProps();
        int port = p.getServerPort();
        new Server().pingPong(port);
    }

    private void pingPong(int port) throws InterruptedException {
        log.fine("which handler?");
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ServerDatagramHandler());
            b.bind(port).sync().channel().closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }
}

这里是DatagramPacket处理程序:

package net.bounceme.dur.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import java.util.Random;
import java.util.logging.Logger;

public class ServerDatagramHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final Logger log = Logger.getLogger(ServerDatagramHandler.class.getName());
    private static final Random random = new Random();

    public ServerDatagramHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static String nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return quotes[quoteId];
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        System.err.println(packet);
        if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
            ctx.write(new DatagramPacket(
                    Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender()));
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.severe(cause.toString());
    }
}

我想切换到Quote处理程序:

package net.bounceme.dur.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Random;
import java.util.logging.Logger;
import net.bounceme.dur.jdbc.Quote;

public class ServerQuoteHandler extends SimpleChannelInboundHandler<Quote> {

    private static final Logger log = Logger.getLogger(ServerQuoteHandler.class.getName());
    private static final Random random = new Random();

    public ServerQuoteHandler() {
        log.info("..started..");
    }

    // Quotes from Mohandas K. Gandhi:
    private static final String[] quotes = {
        "Where there is love there is life.",
        "First they ignore you, then they laugh at you, then they fight you, then you win.",
        "Be the change you want to see in the world.",
        "The weak can never forgive. Forgiveness is the attribute of the strong.",};

    private static String nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return quotes[quoteId];
    }

    @Override
    protected void channelRead0(ChannelHandlerContext chc, Quote quote) throws Exception {
        log.info(quote.toString());
        chc.writeAndFlush(new Quote(nextQuote()));
    }

}

就我的目的而言,Quote它只是一个带有单个字段的String包装器,并toString返回引号。implements Serializable当然,和用途serialVersionUID

当我看乒乓球示例时,我看不到在服务器上添加ObjectEncoder的位置。

博客包含以下代码段:

 // Set up the pipeline factory.
 bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
  public ChannelPipeline getPipeline() throws Exception {
   return Channels.pipeline(
    new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())),
    new DateHandler()
   );
  };
 });

但是,如何在QOTM服务器中实现呢?我正在学习Netty in Action,但是还没有找到相关的文字对此进行解释。既不在书中ObjectEncoder没有ObjectDecoder出现在书中..?

也可以看看:

如何用Netty发送对象?

莫阿

我像这样添加编码器和解码器以发送各种POJO:

客户:

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ObjectEncoder());
            ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            ch.pipeline().addLast(customHandler1);
            ch.pipeline().addLast(customHandler2);
            ch.pipeline().addLast(customHandler3);
        }
    });

服务器:

        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(customHandler1);
                            ch.pipeline().addLast(customHandler2);
                            ch.pipeline().addLast(customHandler3);
                        }
                    });

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何将ObjectDecoder添加到Netty服务器

来自分类Dev

如何将api添加到服务器?

来自分类Dev

Netty将httprequest添加到服务器处理

来自分类Dev

如何将服务器控件动态添加到转发器?

来自分类Dev

如何将https-listener添加到WildFly的默认服务器?

来自分类Dev

如何将Yaml添加到php服务器docker安装中

来自分类Dev

如何将服务器端挂钩添加到GitLab?

来自分类Dev

如何将遥测服务器添加到Nearcore config.json?

来自分类Dev

如何将.jar文件添加到Web服务器的lib目录?

来自分类Dev

如何将CloudWatch Lambda Insights添加到无服务器配置?

来自分类Dev

如何将https-listener添加到WildFly的默认服务器?

来自分类Dev

如何将地理服务器层添加到openlayers?

来自分类Dev

如何将grauphel添加到owncloud服务器

来自分类Dev

如何将多个ip添加到ubuntu 12.04服务器?

来自分类Dev

如何将4.0参考程序集添加到构建服务器(以便编译器找到它们)?

来自分类Dev

如何将共享添加到GraphQL Bin选项到我的Apollo服务器游乐场?

来自分类Dev

如何将CORS-Header添加到我的esp32 Web服务器

来自分类Dev

如何将click事件添加到由服务器端创建的JQuery元素中

来自分类Dev

如何将证书从自签名服务器添加到Chrome中的受信任证书?

来自分类Dev

如何将新的jar文件添加到服务器中现有的已部署jar

来自分类Dev

如何将 pubnub 服务器中的数据以 xamarin 形式添加到列表视图中

来自分类Dev

停用NetworkManager后,如何将DNS服务器地址添加到resolv.conf?

来自分类Dev

如何将自定义Whois服务器添加到WHMCS

来自分类Dev

如何将名称服务器添加到Ubuntu

来自分类Dev

将PubNub添加到聊天服务器

来自分类Dev

将ssh公钥添加到服务器

来自分类Dev

将目录添加到Apache服务器

来自分类Dev

将Glassfish服务器添加到Eclipse Luna

来自分类Dev

将模块添加到解析服务器

Related 相关文章

  1. 1

    如何将ObjectDecoder添加到Netty服务器

  2. 2

    如何将api添加到服务器?

  3. 3

    Netty将httprequest添加到服务器处理

  4. 4

    如何将服务器控件动态添加到转发器?

  5. 5

    如何将https-listener添加到WildFly的默认服务器?

  6. 6

    如何将Yaml添加到php服务器docker安装中

  7. 7

    如何将服务器端挂钩添加到GitLab?

  8. 8

    如何将遥测服务器添加到Nearcore config.json?

  9. 9

    如何将.jar文件添加到Web服务器的lib目录?

  10. 10

    如何将CloudWatch Lambda Insights添加到无服务器配置?

  11. 11

    如何将https-listener添加到WildFly的默认服务器?

  12. 12

    如何将地理服务器层添加到openlayers?

  13. 13

    如何将grauphel添加到owncloud服务器

  14. 14

    如何将多个ip添加到ubuntu 12.04服务器?

  15. 15

    如何将4.0参考程序集添加到构建服务器(以便编译器找到它们)?

  16. 16

    如何将共享添加到GraphQL Bin选项到我的Apollo服务器游乐场?

  17. 17

    如何将CORS-Header添加到我的esp32 Web服务器

  18. 18

    如何将click事件添加到由服务器端创建的JQuery元素中

  19. 19

    如何将证书从自签名服务器添加到Chrome中的受信任证书?

  20. 20

    如何将新的jar文件添加到服务器中现有的已部署jar

  21. 21

    如何将 pubnub 服务器中的数据以 xamarin 形式添加到列表视图中

  22. 22

    停用NetworkManager后,如何将DNS服务器地址添加到resolv.conf?

  23. 23

    如何将自定义Whois服务器添加到WHMCS

  24. 24

    如何将名称服务器添加到Ubuntu

  25. 25

    将PubNub添加到聊天服务器

  26. 26

    将ssh公钥添加到服务器

  27. 27

    将目录添加到Apache服务器

  28. 28

    将Glassfish服务器添加到Eclipse Luna

  29. 29

    将模块添加到解析服务器

热门标签

归档