15815213711
2022-02-14 1c3164c096d405471ad7bb50fce86e321157d8a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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();
    }
}