package com.hdl.sdk.link.socket.udp;
|
|
import android.text.TextUtils;
|
|
import androidx.collection.ArrayMap;
|
|
import com.hdl.sdk.link.common.utils.LogUtils;
|
import com.hdl.sdk.link.common.utils.ThreadToolUtils;
|
import com.hdl.sdk.link.socket.listener.SendListener;
|
import com.hdl.sdk.link.socket.SocketRequest;
|
import com.hdl.sdk.link.socket.client.IUdpClient;
|
|
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
/**
|
* Created by hxb on 2021/12/12.
|
*/
|
public class UdpSocketBoot {
|
|
private final IUdpClient client;
|
|
private final AtomicBoolean isOpenRetry = new AtomicBoolean(false);
|
|
private final AtomicInteger resendCount = new AtomicInteger(0);
|
|
private ExecutorService receiveThread;
|
|
private final ArrayMap<String, SendListener> sendMap = new ArrayMap<>();
|
|
|
public IUdpClient getClient() {
|
return client;
|
}
|
|
public UdpSocketBoot(IUdpClient client) {
|
this.client = client;
|
}
|
|
/**
|
* 绑定 socket
|
* @throws Exception 可能端口冲突
|
*/
|
public void bind() throws Exception {
|
client.bind();
|
initReceiveThread();
|
}
|
|
/**
|
* 初始化接收线程
|
*/
|
private void initReceiveThread() {
|
if(null!=receiveThread){
|
return;
|
}
|
receiveThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
|
receiveThread.execute(new Runnable() {
|
@Override
|
public void run() {
|
while (true) {
|
try {
|
client.onHandleResponse();
|
} catch (Exception e) {
|
LogUtils.i("接收线程异常:"+e.getMessage());
|
}
|
}
|
}
|
});
|
}
|
|
|
/**
|
* 发送数据
|
* @param ipAddress 目的的IP地址
|
* @param port 端口
|
* @param msg 发送数据
|
* @param listener 发送回调
|
*/
|
public void sendMsg(String ipAddress,int port,byte[] msg, SendListener listener) {
|
sendMsg(ipAddress,port, msg, true, listener);
|
}
|
|
/**
|
* 发送数据
|
* @param ipAddress 目的的IP地址
|
* @param port 端口
|
* @param msg 发送数据
|
*/
|
public void sendMsg(String ipAddress,int port,byte[] msg) {
|
sendMsg(ipAddress,port, msg, true, null);
|
}
|
|
/**
|
* 发送数据
|
* @param ipAddress 目的IP地址
|
* @param port 端口
|
* @param msg 发送的数据
|
* @param isRefreshRetry 是否要重发
|
* @param listener 发送回调
|
*/
|
public void sendMsg(String ipAddress,int port, byte[] msg, boolean isRefreshRetry, SendListener listener) {
|
if (isRefreshRetry) {
|
//重置连接次数
|
resendCount.set(0);
|
}
|
try {
|
SocketRequest request = new SocketRequest(msg);
|
if (listener != null && !TextUtils.isEmpty(request.getAction())) {
|
sendMap.put(request.getAction(), listener);
|
}
|
client.sendMsg(ipAddress,port, msg);
|
} catch (Exception e) {
|
LogUtils.e("发送失败:" + e.getMessage());
|
}
|
}
|
|
/**
|
* 关闭当前socket
|
*/
|
public synchronized void close() {
|
isOpenRetry.set(false);
|
sendMap.clear();
|
receiveThread.shutdown();
|
receiveThread=null;
|
client.close();
|
}
|
}
|