java - 如何实现一个可以接受外部信息的Netty客户端?

 Amandadahl 发布于 2022-11-04 14:39
public class NettyClient {
    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);
    private String host;
    private int port;
    private EventLoopGroup workerGroup;
    private Channel channel;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    public NettyClient() {

    }
    public NettyClient connect() {
        workerGroup = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ObjectDecoder(1024, ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline().addLast(new NettyClientHandler());
            }
        });           
        try {
            channel = b.connect(host, port).sync().channel();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

        return this;
    }

    public boolean send(NettyMessage message) {
        logger.debug("sending message111...");
        if(channel != null && channel.isWritable()) {
            logger.debug("send message [{}]", message.getBody());
            channel.write(message);
            return true;
        }else {
            // channel not available
            // cache this message
            logger.debug("cacheing message...");
            cache(message);
            //close();
            connect();          
        }
        return false;
    }

    public void close() {
        workerGroup.shutdownGracefully();
        workerGroup = null;
        if(channel != null) {
            channel.closeFuture().syncUninterruptibly();
            channel = null;
        }

    }

我希望可以这样构建一个client = new NettyClient(host,port).connect();
我在外部运行了一个定时任务,定时采集到信息后,使用client.send(message)来发送数据。
上面的代码只是我的思路,但并没有跑通,在此求助一下。

1 个回答
  • 楼主 怎么解决的,怎么从外部拿到响应信息返回控制层

    2022-11-08 03:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有