This commit is contained in:
wr
2024-12-20 13:28:17 +08:00
parent 5dafcad3fa
commit a81439b1d2
8 changed files with 117 additions and 70 deletions

View File

@@ -21,7 +21,6 @@ import com.njcn.gather.device.device.service.IPqDevService;
import com.njcn.gather.device.script.pojo.param.PqScriptIssueParam; import com.njcn.gather.device.script.pojo.param.PqScriptIssueParam;
import com.njcn.gather.device.script.pojo.po.SourceIssue; import com.njcn.gather.device.script.pojo.po.SourceIssue;
import com.njcn.gather.device.script.service.IPqScriptDtlsService; import com.njcn.gather.device.script.service.IPqScriptDtlsService;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -36,6 +35,8 @@ public class SocketDevResponseService {
private final String handlerStr = "_Dev"; private final String handlerStr = "_Dev";
private final String handlerSourceStr = "_Source";
private final WebSocketHandler webSocketHandler; private final WebSocketHandler webSocketHandler;
private final IPqDevService iPqDevService; private final IPqDevService iPqDevService;
private final IPqScriptDtlsService scriptDtlsService; private final IPqScriptDtlsService scriptDtlsService;
@@ -221,7 +222,7 @@ public class SocketDevResponseService {
successXieyi3.add(mId); successXieyi3.add(mId);
System.out.println(successXieyi3.size() + "=====" + monitorIdListComm.size()); System.out.println(successXieyi3.size() + "=====" + monitorIdListComm.size());
if (successXieyi3.size() == monitorIdListComm.size()) { if (successXieyi3.size() == monitorIdListComm.size()) {
System.out.println("开始相序校验++++++++++"); System.out.println("开始相序校验,向源下参数++++++++++");
PqScriptIssueParam issueParam = new PqScriptIssueParam(); PqScriptIssueParam issueParam = new PqScriptIssueParam();
issueParam.setPlanId(param.getPlanId()); issueParam.setPlanId(param.getPlanId());
issueParam.setSourceId(param.getSourceId()); issueParam.setSourceId(param.getSourceId());
@@ -233,7 +234,7 @@ public class SocketDevResponseService {
xuMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue()); xuMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
xuMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue()); xuMsg.setOperateCode(SourceOperateCodeEnum.OPER_GATHER.getValue());
xuMsg.setData(JSON.toJSONString(sourceIssues.get(0))); xuMsg.setData(JSON.toJSONString(sourceIssues.get(0)));
SocketManager.sendMsg(param.getUserPageId() + "_Source", JSON.toJSONString(xuMsg)); SocketManager.sendMsg(param.getUserPageId() + "_Source", MsgUtil.toJsonWithNewLinePlain(xuMsg));
} }
} }
} }
@@ -288,18 +289,21 @@ public class SocketDevResponseService {
info.addAll(devIsSource(dev, sourceIssues.get(0))); info.addAll(devIsSource(dev, sourceIssues.get(0)));
} }
} }
String s = param.getUserPageId() + "_Source"; String userSource = param.getUserPageId() + handlerSourceStr;
SocketMsg msg = new SocketMsg(); SocketMsg msg = new SocketMsg();
msg.setRequestId(SourceOperateCodeEnum.YJC_YTXJY.getValue()); msg.setRequestId(SourceOperateCodeEnum.YJC_YTXJY.getValue());
msg.setOperateCode(SourceOperateCodeEnum.CLOSE_GATHER.getValue()); msg.setOperateCode(SourceOperateCodeEnum.CLOSE_GATHER.getValue());
Map<String, String> map = new HashMap<>(1); Map<String, String> map = new HashMap<>(1);
map.put("sourceId", sourceIssues.get(0).getSourceId()); map.put("sourceId", sourceIssues.get(0).getSourceId());
msg.setData(JSON.toJSONString(map)); msg.setData(JSON.toJSONString(map));
SocketManager.sendMsg(s, JSON.toJSONString(msg)); SocketManager.sendMsg(userSource, MsgUtil.toJsonWithNewLinePlain(msg));
SocketManager.removeUser(userSource);
SocketManager.removeUser(param.getUserPageId() + handlerStr);
//向前端推送消息 //向前端推送消息
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue()); socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
socketMsg.setOperateCode(socketDataMsg.getOperateCode()); socketMsg.setOperateCode(socketDataMsg.getOperateCode());
socketMsg.setData(JSON.toJSONString(info)); socketMsg.setData(info);
webSocketHandler.sendMsgToUser(param.getUserPageId(), JSON.toJSONString(socketMsg)); webSocketHandler.sendMsgToUser(param.getUserPageId(), JSON.toJSONString(socketMsg));
} }
break; break;
@@ -324,8 +328,13 @@ public class SocketDevResponseService {
private List<SourceCompareDev> devIsSource(DevData dev, SourceIssue issue) { private List<SourceCompareDev> devIsSource(DevData dev, SourceIssue issue) {
List<SourceCompareDev> info = new ArrayList<>(); List<SourceCompareDev> info = new ArrayList<>();
String[] split = dev.getId().split("_"); String[] split = dev.getId().split("_");
String devName = null;
if (devNameMapComm.containsKey(split[0])) {
devName = devNameMapComm.get(split[0]);
}
List<SourceIssue.ChannelListDTO> channelList = issue.getChannelList(); List<SourceIssue.ChannelListDTO> channelList = issue.getChannelList();
List<DevData.SqlDataDTO> sqlData = dev.getSqlData(); List<DevData.SqlDataDTO> sqlData = dev.getSqlData();
@@ -333,10 +342,12 @@ public class SocketDevResponseService {
List<DevData.SqlDataDTO> dataI = sqlData.stream().filter(x -> "电流有效值".equals(x.getDesc())).collect(Collectors.toList()); List<DevData.SqlDataDTO> dataI = sqlData.stream().filter(x -> "电流有效值".equals(x.getDesc())).collect(Collectors.toList());
if (CollUtil.isNotEmpty(dataV)) { if (CollUtil.isNotEmpty(dataV)) {
SourceCompareDev compareDev = getSourceCompareDev(split, dataV, "电压有效值", "U", channelList); SourceCompareDev compareDev = getSourceCompareDev(split, dataV, "电压有效值", "U", channelList);
compareDev.setDevName(devName);
info.add(compareDev); info.add(compareDev);
} }
if (CollUtil.isNotEmpty(dataI)) { if (CollUtil.isNotEmpty(dataI)) {
SourceCompareDev compareDev = getSourceCompareDev(split, dataI, "电流有效值", "I", channelList); SourceCompareDev compareDev = getSourceCompareDev(split, dataI, "电流有效值", "I", channelList);
compareDev.setDevName(devName);
info.add(compareDev); info.add(compareDev);
} }
@@ -360,6 +371,7 @@ public class SocketDevResponseService {
List<SourceIssue.ChannelListDTO> channelList List<SourceIssue.ChannelListDTO> channelList
) { ) {
SourceCompareDev compareDev = new SourceCompareDev(); SourceCompareDev compareDev = new SourceCompareDev();
compareDev.setIp(split[0]); compareDev.setIp(split[0]);
compareDev.setLineNum(split[1]); compareDev.setLineNum(split[1]);
compareDev.setDesc(name); compareDev.setDesc(name);
@@ -413,6 +425,7 @@ public class SocketDevResponseService {
this.successComm = new ArrayList<>(); this.successComm = new ArrayList<>();
this.successXieyi = new ArrayList<>(); this.successXieyi = new ArrayList<>();
this.successXieyi3 = new ArrayList<>(); this.successXieyi3 = new ArrayList<>();
//初始化相序集合
this.devInfo = new ArrayList<>(); this.devInfo = new ArrayList<>();
this.success = new ArrayList<>(); this.success = new ArrayList<>();

View File

@@ -15,7 +15,6 @@ import com.njcn.gather.detection.util.socket.cilent.NettyDevClientHandler;
import com.njcn.gather.detection.util.socket.web.WebSocketHandler; import com.njcn.gather.detection.util.socket.web.WebSocketHandler;
import com.njcn.gather.device.device.pojo.vo.PreDetection; import com.njcn.gather.device.device.pojo.vo.PreDetection;
import com.njcn.gather.device.device.service.IPqDevService; import com.njcn.gather.device.device.service.IPqDevService;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -37,17 +36,20 @@ public class SocketSourceResponseService {
private final SocketDevResponseService socketDevResponseService; private final SocketDevResponseService socketDevResponseService;
private final IPqDevService iPqDevService; private final IPqDevService iPqDevService;
private final String DEV = "_Dev";
@Value("${socket.device.ip}") @Value("${socket.device.ip}")
private String ip; private String ip;
@Value("${socket.device.port}") @Value("${socket.device.port}")
private Integer port; private Integer port;
public void deal(PreDetectionParam param, String msg){
public void deal(PreDetectionParam param, String msg) {
SocketDataMsg socketDataMsg = MsgUtil.socketDataMsg(msg); SocketDataMsg socketDataMsg = MsgUtil.socketDataMsg(msg);
SourceOperateCodeEnum enumByCode = SourceOperateCodeEnum.getDictDataEnumByCode(socketDataMsg.getRequestId()); SourceOperateCodeEnum enumByCode = SourceOperateCodeEnum.getDictDataEnumByCode(socketDataMsg.getRequestId());
if(ObjectUtil.isNotNull(enumByCode)){ if (ObjectUtil.isNotNull(enumByCode)) {
switch (enumByCode){ switch (enumByCode) {
case YJC_YTXJY: case YJC_YTXJY:
detectionDev(param, socketDataMsg); detectionDev(param, socketDataMsg);
break; break;
@@ -56,7 +58,7 @@ public class SocketSourceResponseService {
break; break;
} }
}else{ } else {
System.out.println("1"); System.out.println("1");
} }
@@ -65,20 +67,24 @@ public class SocketSourceResponseService {
/** /**
* 装置检测(当源初始化成功后,直接向装置通道向装置服务器发送,装置检测) * 装置检测(当源初始化成功后,直接向装置通道向装置服务器发送,装置检测)
*
* @param param * @param param
* @param socketDataMsg * @param socketDataMsg
*/ */
private void detectionDev(PreDetectionParam param, SocketDataMsg socketDataMsg) { private void detectionDev(PreDetectionParam param, SocketDataMsg socketDataMsg) {
SourceResponseCodeEnum dictDataEnumByCode = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode()); SourceResponseCodeEnum dictDataEnumByCode = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode());
if(ObjectUtil.isNotNull(dictDataEnumByCode)){ if (ObjectUtil.isNotNull(dictDataEnumByCode)) {
SocketMsg socketMsg=new SocketMsg(); SocketMsg socketMsg;
switch (dictDataEnumByCode){ switch (dictDataEnumByCode) {
case SUCCESS: case SUCCESS:
//todo 前端推送收到的消息暂未处理好 socketMsg = new SocketMsg();
webSocketHandler.sendMsgToUser(param.getUserPageId(), "msg"); socketMsg.setRequestId(SourceOperateCodeEnum.YJC_YTXJY.getValue());
String s = param.getUserPageId() + "_Dev"; socketMsg.setOperateCode(socketDataMsg.getOperateCode());
//开始设备通讯检测(发送设备初始化) socketMsg.setData("源通讯校验成功");
webSocketHandler.sendMsgToUser(param.getUserPageId(), JSON.toJSONString(socketMsg));
SocketManager.removeUser(param.getUserPageId()+"_Source");
//开始设备通讯检测(发送设备初始化)
List<PreDetection> devList = iPqDevService.getDevInfo(param.getDevIds()); List<PreDetection> devList = iPqDevService.getDevInfo(param.getDevIds());
Map<String, List<PreDetection>> map = new HashMap(1); Map<String, List<PreDetection>> map = new HashMap(1);
map.put("deviceList", devList); map.put("deviceList", devList);
@@ -87,12 +93,12 @@ public class SocketSourceResponseService {
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_INIT_GATHER_01.getValue()); socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_INIT_GATHER_01.getValue());
socketMsg.setData(jsonString); socketMsg.setData(jsonString);
String json = JSON.toJSONString(socketMsg); String json = JSON.toJSONString(socketMsg);
NettyClient.socketClient(ip, port, param.getUserPageId(),json, new NettyDevClientHandler(param, socketDevResponseService)); NettyClient.socketClient(ip, port, param.getUserPageId(), json, new NettyDevClientHandler(param, socketDevResponseService));
// SocketManager.sendMsg(s,json);
break; break;
case UNPROCESSED_BUSINESS: case UNPROCESSED_BUSINESS:
break; break;
default: default:
socketMsg = new SocketMsg();
socketMsg.setRequestId(socketDataMsg.getRequestId()); socketMsg.setRequestId(socketDataMsg.getRequestId());
socketMsg.setOperateCode(socketDataMsg.getOperateCode()); socketMsg.setOperateCode(socketDataMsg.getOperateCode());
socketMsg.setData(dictDataEnumByCode.getMessage()); socketMsg.setData(dictDataEnumByCode.getMessage());
@@ -104,14 +110,15 @@ public class SocketSourceResponseService {
/** /**
* 相序检测向装置发送(当装置初始成功后,会向源发送加量请求。收到加量请求成功后会向装置发送参数下发。) * 相序检测向装置发送(当装置初始成功后,会向源发送加量请求。收到加量请求成功后会向装置发送参数下发。)
*
* @param param * @param param
* @param socketDataMsg * @param socketDataMsg
*/ */
private void phaseSequenceDev(PreDetectionParam param, SocketDataMsg socketDataMsg) { private void phaseSequenceDev(PreDetectionParam param, SocketDataMsg socketDataMsg) {
SourceResponseCodeEnum dictDataEnumByCode = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode()); SourceResponseCodeEnum dictDataEnumByCode = SourceResponseCodeEnum.getDictDataEnumByCode(socketDataMsg.getCode());
if(ObjectUtil.isNotNull(dictDataEnumByCode)){ if (ObjectUtil.isNotNull(dictDataEnumByCode)) {
SocketMsg socketMsg=new SocketMsg(); SocketMsg socketMsg = new SocketMsg();
switch (dictDataEnumByCode){ switch (dictDataEnumByCode) {
case SUCCESS: case SUCCESS:
//向前端推送信息 //向前端推送信息
socketMsg.setRequestId(socketDataMsg.getRequestId()); socketMsg.setRequestId(socketDataMsg.getRequestId());
@@ -119,21 +126,20 @@ public class SocketSourceResponseService {
socketMsg.setData(dictDataEnumByCode.getMessage()); socketMsg.setData(dictDataEnumByCode.getMessage());
webSocketHandler.sendMsgToUser(param.getUserPageId(), JSON.toJSONString(socketMsg)); webSocketHandler.sendMsgToUser(param.getUserPageId(), JSON.toJSONString(socketMsg));
String s = param.getUserPageId() + DEV;
String s = param.getUserPageId() + "_Dev";
socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue()); socketMsg.setRequestId(SourceOperateCodeEnum.YJC_XUJY.getValue());
socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue()); socketMsg.setOperateCode(SourceOperateCodeEnum.DEV_DATA_REQUEST_02.getValue());
List<PreDetection> pqDevList = iPqDevService.getDevInfo(param.getDevIds()); List<PreDetection> pqDevList = iPqDevService.getDevInfo(param.getDevIds());
List<String> moniterIdList = pqDevList.stream().flatMap(x -> x.getMonitorList().stream()) List<String> moniterIdList = pqDevList.stream().flatMap(x -> x.getMonitorList().stream())
.map(PreDetection.MonitorListDTO::getLineId) .map(PreDetection.MonitorListDTO::getLineId)
.collect(Collectors.toList()); .collect(Collectors.toList());
DevPhaseSequenceParam phaseSequenceParam=new DevPhaseSequenceParam(); DevPhaseSequenceParam phaseSequenceParam = new DevPhaseSequenceParam();
phaseSequenceParam.setMoniterIdList(moniterIdList); phaseSequenceParam.setMoniterIdList(moniterIdList);
phaseSequenceParam.setDataType(Arrays.asList("实时数据/电压有效值","实时数据/电流有效值")); phaseSequenceParam.setDataType(Arrays.asList("实时数据/电压有效值", "实时数据/电流有效值"));
phaseSequenceParam.setReadCount(1); phaseSequenceParam.setReadCount(1);
phaseSequenceParam.setIgnoreCount(10); phaseSequenceParam.setIgnoreCount(10);
socketMsg.setData(JSON.toJSONString(phaseSequenceParam)); socketMsg.setData(JSON.toJSONString(phaseSequenceParam));
SocketManager.sendMsg(s,JSON.toJSONString(socketMsg)); SocketManager.sendMsg(s, JSON.toJSONString(socketMsg));
break; break;
case UNPROCESSED_BUSINESS: case UNPROCESSED_BUSINESS:
break; break;

View File

@@ -1,11 +1,9 @@
package com.njcn.gather.detection.service.impl; package com.njcn.gather.detection.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException; import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.handler.SocketDevResponseService; import com.njcn.gather.detection.handler.SocketDevResponseService;
import com.njcn.gather.detection.handler.SocketSourceResponseService; import com.njcn.gather.detection.handler.SocketSourceResponseService;
@@ -15,9 +13,9 @@ import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.vo.SocketMsg; import com.njcn.gather.detection.pojo.vo.SocketMsg;
import com.njcn.gather.detection.service.PreDetectionService; import com.njcn.gather.detection.service.PreDetectionService;
import com.njcn.gather.detection.util.socket.MsgUtil;
import com.njcn.gather.detection.util.socket.SocketManager; import com.njcn.gather.detection.util.socket.SocketManager;
import com.njcn.gather.detection.util.socket.cilent.NettyClient; import com.njcn.gather.detection.util.socket.cilent.NettyClient;
import com.njcn.gather.detection.util.socket.cilent.NettyDevClientHandler;
import com.njcn.gather.detection.util.socket.cilent.NettySourceClientHandler; import com.njcn.gather.detection.util.socket.cilent.NettySourceClientHandler;
import com.njcn.gather.device.device.service.IPqDevService; import com.njcn.gather.device.device.service.IPqDevService;
import com.njcn.gather.device.script.service.IPqScriptDtlsService; import com.njcn.gather.device.script.service.IPqScriptDtlsService;
@@ -34,8 +32,6 @@ import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service @Service
@@ -102,7 +98,7 @@ public class PreDetectionServiceImpl implements PreDetectionService {
msg.setOperateCode(SourceOperateCodeEnum.INIT_GATHER.getValue()); msg.setOperateCode(SourceOperateCodeEnum.INIT_GATHER.getValue());
msg.setData(JSON.toJSONString(sourceParam)); msg.setData(JSON.toJSONString(sourceParam));
param.setSourceId(sourceParam.getSourceId()); param.setSourceId(sourceParam.getSourceId());
NettyClient.socketClient(ip, port, param.getUserPageId(), JSON.toJSONString(msg), new NettySourceClientHandler(param, sourceResponseService)); NettyClient.socketClient(ip, port, param.getUserPageId(), MsgUtil.toJsonWithNewLinePlain(msg), new NettySourceClientHandler(param, sourceResponseService));
} else { } else {
throw new BusinessException(DetectionResponseEnum.SOURCE_INFO_NOT); throw new BusinessException(DetectionResponseEnum.SOURCE_INFO_NOT);
} }

View File

@@ -1,6 +1,7 @@
package com.njcn.gather.detection.util.socket; package com.njcn.gather.detection.util.socket;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.njcn.gather.detection.pojo.vo.SocketDataMsg; import com.njcn.gather.detection.pojo.vo.SocketDataMsg;
/** /**
@@ -15,4 +16,24 @@ public class MsgUtil {
public static SocketDataMsg socketDataMsg(String textMsg){ public static SocketDataMsg socketDataMsg(String textMsg){
return JSON.parseObject(textMsg,SocketDataMsg.class); return JSON.parseObject(textMsg,SocketDataMsg.class);
} }
/**
* 将对象转换为 JSON 字符串,并在末尾添加换行符
*
* @param obj 需要转换的对象
* @return 包含换行符的 JSON 字符串
*/
public static String toJsonWithNewLine(Object obj) {
return JSON.toJSONString(obj, SerializerFeature.PrettyFormat) + "\n";
}
/**
* 将对象转换为 JSON 字符串,并在末尾添加换行符(不带格式化)
*
* @param obj 需要转换的对象
* @return 包含换行符的 JSON 字符串
*/
public static String toJsonWithNewLinePlain(Object obj) {
return JSON.toJSONString(obj) + "\n";
}
} }

View File

@@ -2,7 +2,7 @@ package com.njcn.gather.detection.util.socket;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.channel.nio.NioEventLoopGroup;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -14,22 +14,39 @@ import java.util.concurrent.ConcurrentHashMap;
*/ */
public class SocketManager { public class SocketManager {
private static final Map<String, Channel> userSessions = new ConcurrentHashMap<>(); private static final Map<String, Channel> socketSessions = new ConcurrentHashMap<>();
private static final Map<String, NioEventLoopGroup> socketGroup = new ConcurrentHashMap<>();
public static void addUser(String userId, Channel channel) { public static void addUser(String userId, Channel channel) {
userSessions.put(userId, channel); socketSessions.put(userId, channel);
} }
public static void addGroup(String userId, NioEventLoopGroup group) {
socketGroup.put(userId, group);
}
public static void removeUser(String userId) { public static void removeUser(String userId) {
userSessions.remove(userId); Channel channel = socketSessions.get(userId);
if(ObjectUtil.isNotNull(channel)){
channel.close();
NioEventLoopGroup eventExecutors = socketGroup.get(userId);
if(ObjectUtil.isNotNull(channel)){
eventExecutors.shutdownGracefully();
System.out.println(userId+"__"+channel.id()+"关闭了客户端");
}
}
socketSessions.remove(userId);
} }
public static Channel getChannelByUserId(String userId) { public static Channel getChannelByUserId(String userId) {
return userSessions.get(userId); return socketSessions.get(userId);
}
public static NioEventLoopGroup getGroupByUserId(String userId) {
return socketGroup.get(userId);
} }
public static void sendMsg(String userId,String msg) { public static void sendMsg(String userId,String msg) {
Channel channel = userSessions.get(userId); Channel channel = socketSessions.get(userId);
if(ObjectUtil.isNotNull(channel)){ if(ObjectUtil.isNotNull(channel)){
channel.writeAndFlush(msg); channel.writeAndFlush(msg);
System.out.println(userId+"__"+channel.id()+""+channel.remoteAddress()+"发送数据:"+msg); System.out.println(userId+"__"+channel.id()+""+channel.remoteAddress()+"发送数据:"+msg);

View File

@@ -1,9 +1,8 @@
package com.njcn.gather.detection.util.socket.cilent; package com.njcn.gather.detection.util.socket.cilent;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum; import com.njcn.gather.detection.pojo.enums.SourceResponseCodeEnum;
import com.njcn.gather.detection.pojo.vo.WebSocketVO; import com.njcn.gather.detection.pojo.vo.WebSocketVO;
import com.njcn.gather.detection.util.socket.SocketManager; import com.njcn.gather.detection.util.socket.SocketManager;
@@ -13,21 +12,12 @@ import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.TimeoutException;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import lombok.Data;
import lombok.Getter; import lombok.Getter;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
@@ -79,6 +69,16 @@ public class NettyClient {
channelFuture.channel().writeAndFlush(msg); channelFuture.channel().writeAndFlush(msg);
} }
}); });
NioEventLoopGroup groupByUserId = SocketManager.getGroupByUserId(userPageId + "_Dev");
if(ObjectUtil.isNotNull(groupByUserId)){
groupByUserId.shutdownGracefully();
}else{
if (handler instanceof NettySourceClientHandler) {
SocketManager.addGroup(userPageId+"_Source",group);
}else{
SocketManager.addGroup(userPageId+"_Dev",group);
}
}
} catch (Exception e) { } catch (Exception e) {
System.out.println("连接socker服务端发送异常............" + e.getMessage()); System.out.println("连接socker服务端发送异常............" + e.getMessage());
group.shutdownGracefully(); group.shutdownGracefully();

View File

@@ -8,7 +8,6 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.TimeoutException; import io.netty.handler.timeout.TimeoutException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import java.io.IOException; import java.io.IOException;
import java.net.ConnectException; import java.net.ConnectException;
@@ -29,12 +28,6 @@ public class NettyDevClientHandler extends SimpleChannelInboundHandler<String> {
private final SocketDevResponseService socketResponseService; private final SocketDevResponseService socketResponseService;
@Value("${socket.device.ip}")
private String devIp;
@Value("${socket.device.port}")
private Integer devPort;
/** /**
* 当通道进行连接时推送消息 * 当通道进行连接时推送消息

View File

@@ -1,10 +1,10 @@
package com.njcn.gather.detection.util.socket.cilent; package com.njcn.gather.detection.util.socket.cilent;
import com.alibaba.fastjson.JSON;
import com.njcn.gather.detection.handler.SocketSourceResponseService; import com.njcn.gather.detection.handler.SocketSourceResponseService;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum; import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.pojo.param.PreDetectionParam; import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.pojo.vo.SocketMsg; import com.njcn.gather.detection.pojo.vo.SocketMsg;
import com.njcn.gather.detection.util.socket.MsgUtil;
import com.njcn.gather.detection.util.socket.SocketManager; import com.njcn.gather.detection.util.socket.SocketManager;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
@@ -27,24 +27,24 @@ import java.util.Objects;
*/ */
@RequiredArgsConstructor @RequiredArgsConstructor
public class NettySourceClientHandler extends SimpleChannelInboundHandler<String> { public class NettySourceClientHandler extends SimpleChannelInboundHandler<String> {
private final PreDetectionParam webUser; private final PreDetectionParam webUser;
private final SocketSourceResponseService sourceResponseService; private final SocketSourceResponseService sourceResponseService;
/** /**
* 当通道进行连接时推送消息 * 当通道进行连接时推送消息
*
* @param ctx * @param ctx
*/ */
@Override @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客户端通道已建立" + ctx.channel().id()); System.out.println("客户端通道已建立" + ctx.channel().id());
Channel channel = SocketManager.getChannelByUserId(webUser.getUserPageId()+"_Source"); Channel channel = SocketManager.getChannelByUserId(webUser.getUserPageId() + "_Source");
if(Objects.nonNull(channel)){ if (Objects.nonNull(channel)) {
channel.close(); channel.close();
} }
SocketManager.addUser(webUser.getUserPageId()+"_Source",ctx.channel()); SocketManager.addUser(webUser.getUserPageId() + "_Source", ctx.channel());
System.out.println("一存储");
} }
/** /**
@@ -52,14 +52,15 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<Strin
*/ */
@Override @Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws InterruptedException { protected void channelRead0(ChannelHandlerContext ctx, String msg) throws InterruptedException {
System.out.println("接收server端数据>>>>>>"+msg); System.out.println("接收server端数据>>>>>>" + msg);
sourceResponseService.deal(webUser,msg); sourceResponseService.deal(webUser, msg);
} }
/** /**
* 当通道断线时,支持重连 * 当通道断线时,支持重连
*
* @param ctx * @param ctx
*/ */
@Override @Override
@@ -84,14 +85,14 @@ public class NettySourceClientHandler extends SimpleChannelInboundHandler<Strin
if (evt instanceof IdleStateEvent) { if (evt instanceof IdleStateEvent) {
if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) { if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
//发送ping 保持心跳链接 //发送ping 保持心跳链接
SocketMsg msg=new SocketMsg(); SocketMsg msg = new SocketMsg();
msg.setRequestId("yxt"); msg.setRequestId("yxt");
msg.setOperateCode(SourceOperateCodeEnum.HEARTBEAT.getValue()); msg.setOperateCode(SourceOperateCodeEnum.HEARTBEAT.getValue());
msg.setData(""); msg.setData("");
ctx.writeAndFlush(JSON.toJSONString(msg)); ctx.writeAndFlush(MsgUtil.toJsonWithNewLinePlain(msg));
} }
}else { } else {
userEventTriggered(ctx,evt); userEventTriggered(ctx, evt);
} }
} }