|
@@ -0,0 +1,61 @@
|
|
|
|
+package com.kingtom.shengtai.app.message.ws;
|
|
|
|
+
|
|
|
|
+import java.time.LocalDateTime;
|
|
|
|
+
|
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
|
+import org.springframework.web.socket.BinaryMessage;
|
|
|
|
+import org.springframework.web.socket.CloseStatus;
|
|
|
|
+import org.springframework.web.socket.TextMessage;
|
|
|
|
+import org.springframework.web.socket.WebSocketSession;
|
|
|
|
+import org.springframework.web.socket.handler.AbstractWebSocketHandler;
|
|
|
|
+
|
|
|
|
+/**
|
|
|
|
+ * 应用模块名称</p>
|
|
|
|
+ * 代码描述</p>
|
|
|
|
+ * Copyright: Copyright (C) 2023 , Inc. All rights reserved. <p>
|
|
|
|
+ * Company: 成都诚唐科技有限责任公司</p>
|
|
|
|
+ *
|
|
|
|
+ * @author wany
|
|
|
|
+ * @since 2023/12/26
|
|
|
|
+ */
|
|
|
|
+@Slf4j
|
|
|
|
+public class WsHandler extends AbstractWebSocketHandler{
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public void afterConnectionEstablished(WebSocketSession session) throws Exception{
|
|
|
|
+ log.info("建立ws连接");
|
|
|
|
+ String key = session.getAttributes().get("userId").toString();
|
|
|
|
+ WsSessionManager.add(key, session);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception{
|
|
|
|
+ log.info("发送文本消息");
|
|
|
|
+ // 获得客户端传来的消息
|
|
|
|
+ String payload = message.getPayload();
|
|
|
|
+ log.info("server 接收到消息 " + payload);
|
|
|
|
+ session.sendMessage(new TextMessage("server 发送给的消息 " + payload + ",发送时间:" + LocalDateTime.now()));
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception{
|
|
|
|
+ log.info("发送二进制消息");
|
|
|
|
+ session.sendMessage(message);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception{
|
|
|
|
+ log.error("异常处理");
|
|
|
|
+ String key = session.getAttributes().get("userId").toString();
|
|
|
|
+ WsSessionManager.removeAndClose(key);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception{
|
|
|
|
+ log.info("关闭ws连接");
|
|
|
|
+ String key = session.getAttributes().get("userId").toString();
|
|
|
|
+ WsSessionManager.removeAndClose(key);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+}
|
|
|
|
+
|