zhuguifei
2026-03-10 2c1fd10c6fbabb8e9f0e9f07fe66fb36c008e883
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.shlanbao.tzsc.pms.websocket;
 
import org.apache.commons.collections.MapUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
 
/**
 
 */
public class MyWebSocketHandler extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String userId = MapUtils.getString(session.getAttributes(),"name");
        System.out.println("websocket连接:用户-" +userId);
        //记录连接的session
        if(userId!=null)
        WebSocketSessionUtils.getInstance().add(userId,session);
 
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        String userId = MapUtils.getString(session.getAttributes(),"name");
              //回复消息
//            TextMessage returnMessage = new TextMessage("Hi:"+userId+"..your message:"+message.getPayload()+" I have received,now I tell you");
//            WebSocketSessionUtils.getInstance().sendMessageToTarget(userId,returnMessage);
 
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        String userId = MapUtils.getString(session.getAttributes(),"name");
        System.out.println("websocket错误:用户-" +userId+"/错误-"+exception.toString());
        WebSocketSessionUtils.getInstance().remove(userId);
    }
 
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
 
        String userId = MapUtils.getString(session.getAttributes(),"name");
        System.out.println("websocket断开:用户-" +userId);
        WebSocketSessionUtils.getInstance().remove(userId);
    }
}