com.feingto.iot.client.bootstrap.CustomClientBootstrap Maven / Gradle / Ivy
package com.feingto.iot.client.bootstrap;
import com.feingto.iot.client.config.NettyProperties;
import com.feingto.iot.client.handler.CustomClientChannelHandler;
import com.feingto.iot.common.bootstrap.SimpleHandlerLoader;
import com.feingto.iot.common.model.mqtt.MqttConnectOptions;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 自定义消息客户端启动器
*
* @author longfei
*/
public class CustomClientBootstrap extends BaseBootstrap {
public CustomClientBootstrap(NettyProperties config) {
super(config);
}
public Bootstrap init() {
group = new NioEventLoopGroup(config.getWorkThread(), new DefaultThreadFactory("CLIENT_"));
MqttConnectOptions options = config.getMqtt();
return new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getTimeout())
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) {
if (options.getKeepAliveInterval() > 0) {
ch.pipeline()
.addLast(new IdleStateHandler(0,
options.getKeepAliveInterval(), 0, TimeUnit.SECONDS));
}
List handlers = SimpleHandlerLoader.getTcpHandlers();
handlers.add(new IdleStateHandler(0, 1, 0, TimeUnit.MINUTES));
handlers.add(new CustomClientChannelHandler());
handlers.forEach(handler -> ch.pipeline().addLast(handler));
}
});
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy