package com.xncoding.pos.handler;
|
import java.net.InetSocketAddress;
|
|
import com.xncoding.pos.config.NettyProperties;
|
import com.xncoding.pos.utils.ApplicationContextUtils;
|
import com.xncoding.pos.utils.RunShellUtils;
|
import com.xncoding.pos.utils.SmsUtils;
|
import io.netty.bootstrap.Bootstrap;
|
import io.netty.channel.ChannelFuture;
|
import io.netty.channel.ChannelInitializer;
|
import io.netty.channel.nio.NioEventLoopGroup;
|
import io.netty.channel.socket.SocketChannel;
|
import io.netty.channel.socket.nio.NioSocketChannel;
|
import io.netty.handler.codec.string.StringDecoder;
|
import io.netty.handler.codec.string.StringEncoder;
|
import io.netty.handler.timeout.IdleStateHandler;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
public class ClientStarter {
|
|
private static final Logger logger = LoggerFactory.getLogger(ClientStarter.class);
|
|
private static NettyProperties config;
|
|
private final Bootstrap bootstrap;
|
|
public ClientStarter(Bootstrap bootstrap) {
|
if(config == null){
|
config = (NettyProperties)ApplicationContextUtils.getBean("nettyProperties");
|
}
|
this.bootstrap = bootstrap;
|
ClientStarter clientStarter = this;
|
bootstrap.group(new NioEventLoopGroup())
|
.channel(NioSocketChannel.class)
|
.handler(new ChannelInitializer<SocketChannel>() {
|
@Override
|
protected void initChannel(SocketChannel ch) throws Exception {
|
ch.pipeline().addLast(new StringEncoder());
|
ch.pipeline().addLast(new StringDecoder());
|
//发送消息频率。单位秒。此设置是5秒发送一次消息
|
ch.pipeline().addLast(new IdleStateHandler(config.getTimeSeconds(), config.getTimeSeconds(), config.getTimeSeconds()));
|
ch.pipeline().addLast(new HeartBeatClientHandler(clientStarter));
|
}
|
});
|
}
|
|
public void connect() {
|
|
ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(config.getUrl(), config.getPort()));
|
channelFuture.addListener(future ->{
|
if (future.isSuccess()) {
|
logger.info("连接服务成功");
|
} else {
|
logger.info("服务ping失败");
|
Thread.sleep(5000);
|
connect();
|
}
|
});
|
}
|
|
|
|
|
public static void main(String[] args) {
|
ClientStarter starter = new ClientStarter(new Bootstrap());
|
starter.connect();
|
}
|
}
|