消息推送连接关闭时避免报错

This commit is contained in:
2024-10-01 10:29:06 +08:00
parent f19a15dbe8
commit 283b6244b1
2 changed files with 14 additions and 2 deletions

View File

@@ -87,7 +87,19 @@ public class NotificationConnection {
// 判断用户ID与当前的Key相等
if (userId.equals(key)) {
log.info("私发消息 【给用户】 {}发送消息【{}】", key, message); // 打印
webSocket.session.getBasicRemote().sendText(message); // 则发送给当前的用户即可
if (webSocket.session.isOpen()){
// 避免因为网络问题或其他原因导致连接突然关闭而报错
try {
webSocket.session.getBasicRemote().sendText(message); // 则发送给当前的用户即可
} catch (IOException e) {
log.error("Failed to send message to session {}: {}", webSocket.session.getId(), e.getMessage());
// 这里可以选择移除关闭的 session
websockets.remove(entry.getKey());
}
}else {
log.info("连接已关闭sessionId:{}, userId:{}", webSocket.session.getId(), key);
websockets.remove(entry.getKey());
}
}
}
}

View File

@@ -196,7 +196,7 @@ public class MessageCenterServiceImpl extends ServiceImpl<NotificationMapper, No
data.put(type, count);
resp.add(data);
String jsonString = JSON.toJSONString(resp);
log.info("消息推送 {}", jsonString);
// log.info("消息推送 {}", jsonString);
try {
notificationConnection.sendMsg(jsonString, receiverId);