hxb
2021-12-12 d8bf4f4d66715f002d024cae92862c1d83daa425
HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java
@@ -1,6 +1,5 @@
package com.hdl.sdk.connect.socket;
import android.net.ipsec.ike.TunnelModeChildSessionParams;
import android.text.TextUtils;
import com.google.gson.Gson;
@@ -30,15 +29,13 @@
import com.hdl.sdk.connect.bean.LinkResponse;
import com.hdl.sdk.connect.protocol.LinkMessageDecoder;
import com.hdl.sdk.connect.protocol.LinkMessageEncoder;
import com.hdl.sdk.socket.SocketBoot;
import com.hdl.sdk.socket.SocketOptions;
import com.hdl.sdk.socket.client.UdpClient;
import com.hdl.sdk.socket.codec.MessagePipeLine;
import com.hdl.sdk.socket.listener.SendListener;
import com.hdl.sdk.socket.udp.UdpSocketBoot;
import com.hdl.sdk.socket.udp.UdpSocketOptions;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -47,7 +44,7 @@
/**
 * Created by jlchen on 11/11/21.
 *
 * @Description : HDLAuthSocket
 * @Description : HDLAuthSocket 由于前期已经命名好,不做更改,可用作Udp服务端使用
 */
public class HDLAuthSocket {
    private static final String TAG = "HDLAuth";
@@ -55,7 +52,10 @@
     * udp默认端口
     */
    private static final int UDP_PORT = 8585;
    private static SocketBoot updBoot;
    /**
     * 因为考虑到使用一个端口,要支持接收多网关的数据,所以只允许使用一个
     */
    private static UdpSocketBoot udpSocketBoot;
    //    private EventListener authEvent;
    //搜索网关
    private EventListener searchGatewayEvent;
@@ -71,6 +71,7 @@
    private HDLAuthSocket() {
        initSearchGatewayEvent();
        initListenerGatewayEvent();
    }
//    public interface CallBack extends BaseCallBack {
@@ -87,30 +88,39 @@
            synchronized (HDLLinkConfig.class) {
                if (instance == null) {
                    instance = new HDLAuthSocket();
                    //1.启动Socket 开启监听
                    instance.getUdpBoot();
                }
            }
        }
        return instance;
    }
    private SocketOptions getUdpOptions() {
        final SocketOptions options = new SocketOptions();
    private UdpSocketOptions getUdpOptions() {
        final UdpSocketOptions options = new UdpSocketOptions();
        final MessagePipeLine pipeLine = new MessagePipeLine();
        pipeLine.add(new LinkMessageDecoder());
        pipeLine.add(new LinkMessageEncoder());
        options.setHandleMessage(pipeLine);
        options.setHeartbeatTimeInterval(10*1000L);
        options.setHeartbeatData("UDP");
        options.setEnabledHeartbeat(true);//是否开启心跳包发送检测
        return options;
    }
    private SocketBoot getUdpBoot(String ip) {
        if (updBoot == null) {
            updBoot = UdpClient.init(ip, UDP_PORT, getUdpOptions());
            updBoot.connect();
    /**
     * 获取当前udp对象,如果不存在就创建
     * @return 返回当前对象
     */
    private UdpSocketBoot getUdpBoot() {
        try {
            if (udpSocketBoot == null) {
                udpSocketBoot = UdpClient.init(UDP_PORT, getUdpOptions());
                udpSocketBoot.bind();
        }
        return updBoot;
        } catch (Exception e) {
            return null;
        }
        return udpSocketBoot;
    }
    /**
@@ -121,8 +131,6 @@
     */
    public void startAuthenticateRequest(AuthenticateRequest request, HDLLinkCallBack callBack) {
        HDLLinkConfig.getInstance().clearConfig();
        //1.启动Socket 开启监听
        getUdpBoot(IpUtils.getBroadcastAddress());
        //2.构建监听Listener
//        authEvent =
        //3.监听网关广播的入网指令
@@ -168,7 +176,7 @@
        String requestStr = gs.toJson(request);
        LinkRequest message = new LinkRequest(topic, requestStr);
        HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() {
        HdlSocketHelper.send(getUdpBoot(), InetSocketAddress.createUnresolved(ip,UDP_PORT), message, new HdlSocketHelper.HdlSocketListener() {
            @Override
            public void onSucceed(Object msg) {
                if (callBack == null) return;
@@ -284,7 +292,7 @@
     * @param callBack 回调
     */
    public void searchGatewayMulticast(SearchGatewayCallBack callBack) {
        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), UDP_GROUP_IP, callBack);
        searchGateway(HDLLinkConfig.getInstance().getGatewayId(),  InetSocketAddress.createUnresolved(UDP_GROUP_IP,UDP_PORT), callBack);
    }
    /**
@@ -294,7 +302,7 @@
     */
    public void searchGatewayBroadcast(SearchGatewayCallBack callBack) {
        String ip = IpUtils.getBroadcastAddress();
        searchGateway(HDLLinkConfig.getInstance().getGatewayId(), ip, callBack);
        searchGateway(HDLLinkConfig.getInstance().getGatewayId(),  InetSocketAddress.createUnresolved(ip,UDP_PORT), callBack);
    }
@@ -312,7 +320,7 @@
                GsonConvert.getGson().toJson(data));
        String ip = IpUtils.getBroadcastAddress();
        HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() {
        HdlSocketHelper.send(getUdpBoot(), InetSocketAddress.createUnresolved(ip,UDP_PORT), message, new HdlSocketHelper.HdlSocketListener() {
            @Override
            public void onSucceed(Object msg) {
                if (callBack == null) return;
@@ -345,7 +353,7 @@
        }
        LinkRequest message = new LinkRequest(topic, bodyStr);
        String ip = IpUtils.getBroadcastAddress();
        HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() {
        HdlSocketHelper.send(getUdpBoot(), InetSocketAddress.createUnresolved(ip,UDP_PORT), message, new HdlSocketHelper.HdlSocketListener() {
                    @Override
                    public void onSucceed(Object msg) {
                        if (callBack == null) return;
@@ -374,7 +382,7 @@
        }
        LinkRequest message = new LinkRequest(topic, bodyStr);
        String ip = IpUtils.getBroadcastAddress();
        getUdpBoot(ip).sendMsg(message.getSendBytes());
        getUdpBoot().sendMsg( InetSocketAddress.createUnresolved(ip,UDP_PORT),message.getSendBytes());
    }
    private GatewaySearchBean getGatewaySearchBean(Object msg) {
@@ -433,7 +441,7 @@
    private SearchGatewayCallBack mSearchGatewayCallBack;
    private void initSearchGatewayEvent() {
        LogUtils.i("搜索网关--", "initSearchGatewayEvent");
        LogUtils.i("搜索网关", "initSearchGatewayEvent");
        searchGatewayEvent = new EventListener() {
            @Override
            public void onMessage(Object msg) {
@@ -441,7 +449,6 @@
                    if (msg instanceof LinkResponse) {
                        LinkResponse linkResponse = (LinkResponse) msg;
                        String data = linkResponse.getData();
                        LogUtils.i("搜索到网关->" + data);
                        if (!TextUtils.isEmpty(data)) {
                            final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() {
                            }.getType());
@@ -467,14 +474,44 @@
        };
    }
    private void initListenerGatewayEvent() {
        LogUtils.i( "初始化永久监听网关广播事件,不用移除此事件");
        EventListener  gatewayEvent = new EventListener() {
            @Override
            public void onMessage(Object msg) {
                try {
                    if (msg instanceof LinkResponse) {
                        LinkResponse linkResponse = (LinkResponse) msg;
                        String data = linkResponse.getData();
                        LogUtils.i("接收到网关信息:" + data);
                        if (!TextUtils.isEmpty(data)) {
                            final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() {
                            }.getType());
                            GatewaySearchBean searchBean = response.getObjects();
                            if (searchBean != null && !TextUtils.isEmpty(searchBean.getGatewayId())) {
                                if (searchBean.getGatewayId().equals(HDLLinkConfig.getInstance().getGatewayId())) {
                                    HDLLinkConfig.getInstance().setCurrentGateway(searchBean);//设置当前网关
                                    HDLLinkConfig.getInstance().setLocalEncrypt(searchBean.isLocalEncrypt());//设置是否加密
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
        };
        EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, gatewayEvent);
    }
    /**
     * 搜索指定网关是否在线,搜索到则返回指定的网关对象
     *
     * @param gatewayId 网关id
     * @param ip        接收目标的ip地址
     * @param desInetSocketAddress        目标的地址
     * @param callBack  回调
     */
    public void searchGateway(String gatewayId, String ip, SearchGatewayCallBack callBack) {
    public void searchGateway(String gatewayId, InetSocketAddress desInetSocketAddress, SearchGatewayCallBack callBack) {
        this.searchGatewayId = gatewayId;
        this.mSearchGatewayCallBack = callBack;
        //重置参数
@@ -495,8 +532,8 @@
                    try {
                        //搜索网关
                        searchGatewayCount.set(searchGatewayCount.get() + 1);
                        LogUtils.i("搜索网关--", "搜索网关第" + searchGatewayCount.get() + "次");
                        getUdpBoot(ip).sendMsg(message.getSendBytes());
                        LogUtils.i("搜索网关", "搜索网关第" + searchGatewayCount.get() + "次");
                        getUdpBoot().sendMsg(desInetSocketAddress,message.getSendBytes());
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
@@ -517,7 +554,7 @@
     * 注册搜索网关监听
     */
    private void registerSearchGatewayEvent() {
        LogUtils.i("搜索网关--", "注册搜索网关监听");
        LogUtils.i("搜索网关", "注册搜索网关监听");
        EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, searchGatewayEvent);
    }
@@ -525,7 +562,7 @@
     * 移除搜索网关监听
     */
    private void removeSearchGatewayEvent() {
        LogUtils.i("搜索网关--", "移除搜索网关监听");
        LogUtils.i("搜索网关", "移除搜索网关监听");
        EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_SEARCH_REPLY, searchGatewayEvent);
    }