java - 如何实现一个可以接受外部信息的Netty客户端?
PHP中文网
PHP中文网 2017-04-17 13:51:20
[Java讨论组]
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<SocketChannel>() {
            @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)来发送数据。
上面的代码只是我的思路,但并没有跑通,在此求助一下。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
迷茫

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号