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



 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) 来发送数据。
上面的代码只是我的思路,但并没有跑通,在此求助一下。

java netty

神奇IP君 10 years, 4 months ago

Your Answer