(澳门新葡京官方网站) 如何实现一个可以接受外部信息的Netty客户端?
澳门新葡京
澳门新葡京
当前位置 : 澳门新葡京 > 澳门新葡京官方网站

(澳门新葡京官方网站) 如何实现一个可以接受外部信息的Netty客户端?

public class NettyClient {
    private static final Logger logger = LoggerFactory.getLoggerNettyClient.class;
    private String host;
    private int port;
    private EventLoopGroup workerGroup;
    private Channel channel;

    public NettyClientString host, int port {
        this.host = host;
        this.port = port;
    }
    public NettyClient {

    }
    public NettyClient connect {
        workerGroup = new NioEventLoopGroup;

        Bootstrap b = new Bootstrap; // 1
        b.groupworkerGroup; // 2
        b.channelNioSocketChannel.class; // 3
        b.optionChannelOption.SO_KEEPALIVE, true; // 4
        b.handlernew ChannelInitializer<SocketChannel> {
            @Override
            public void initChannelSocketChannel ch throws Exception {
                ch.pipeline.addLastnew ObjectDecoder1024, ClassResolvers.cacheDisabledthis.getClass.getClassLoader;
                ch.pipeline.addLastnew ObjectEncoder;
                ch.pipeline.addLastnew NettyClientHandler;
            }
        };           
        try {
            channel = b.connecthost, port.sync.channel;

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

        return this;
    }

    public boolean sendNettyMessage message {
        logger.debug"sending message111...";
        ifchannel != null && channel.isWritable {
            logger.debug"send message [{}]", message.getBody;
            channel.writemessage;
            return true;
        }else {
            // channel not available
            // cache this message
            logger.debug"cacheing message...";
            cachemessage;
            //close;
            connect;          
        }
        return false;
    }

    public void close {
        workerGroup.shutdownGracefully;
        workerGroup = null;
        ifchannel != null {
            channel.closeFuture.syncUninterruptibly;
            channel = null;
        }

    }

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

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

该答案已被忽略,原因:不符合答题规范:内容不是答案,可用评论、投票替代

广告位

澳门新葡京