liusuyi
2024-07-17 2ab35000026ccd58238e6a504b1b5f79f8c262c3
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package com.ruoyi.utils.websocket.service;
 
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.app.position.service.impl.AppPositionPushService;
import com.ruoyi.call.dto.CallMessage;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.utils.websocket.util.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import static com.ruoyi.utils.websocket.util.WebSocketUtils.ONLINE_USER_SESSIONS;
 
/**
 * @ClassName ChatServerEndpoint
 * @Description: websocket操作类
 * @Author 刘苏义
 * @Date 2023/1/27 7:42
 * @Version 1.0
 */
 
@Component
@Slf4j(topic = "websocket")
@ServerEndpoint("/websocket/{userId}")
public class ChatServerEndpoint {
    @OnOpen
    public void openSession(@PathParam("userId") String userId, Session session) {
        WebSocketUtils.ONLINE_USER_SESSIONS.put(userId, session);
        String message = "用户[" + userId + "] 成功连接!";
        log.info("用户登录:" + message);
        WebSocketUtils.sendMessage(session, message);
    }
 
    @OnMessage
    public void onMessage(@PathParam("userId") String userId, String message) {
        log.debug("收到消息:" + message);
        Map<String, Object> messageMap = JSONObject.parseObject(message, Map.class);
        if (messageMap.get("type").equals("callMessage")) {
            String msg = (String) messageMap.get("message");
            CallMessage callMessage = JSONObject.parseObject(msg, CallMessage.class);
            //单聊
            if (callMessage != null && callMessage.getType().equals(0)) {
                WebSocketUtils.sendMessagePrefix(callMessage.getTargetId(), message);
            }
            //群聊
            if (callMessage != null && callMessage.getType().equals(1)) {
                String step = callMessage.getStep();
                switch (step) {
                    case "joinRoom":
                        Set<String> userSet = WebSocketUtils.ROOM_USER_SET.getOrDefault(callMessage.getRoomId(), new HashSet<>());
                        userSet.add(callMessage.getUserId());
                        WebSocketUtils.ROOM_USER_SET.put(callMessage.getRoomId(), userSet);
                        WebSocketUtils.sendRoomMessage(callMessage.getRoomId(), message);
                        break;
                    case "inviteRoom":
                        List<String> targetIds = callMessage.getTargetIds();
                        targetIds.stream().forEach(targetId -> {
                            WebSocketUtils.sendMessagePrefix(targetId, message);
                        });
                        break;
                    case "leaveRoom":
                        userSet = WebSocketUtils.ROOM_USER_SET.getOrDefault(callMessage.getRoomId(), new HashSet<>());
                        if (userSet.size() > 0) {
                            userSet.remove(callMessage.getUserId());
                            WebSocketUtils.ROOM_USER_SET.put(callMessage.getRoomId(), userSet);
                            WebSocketUtils.sendRoomMessage(callMessage.getRoomId(), message);
                        }
                        break;
                    default:
                        WebSocketUtils.sendMessagePrefix(callMessage.getTargetId(), message);
                        break;
                }
 
 
            }
        }
        // 根据用户新的频率重新调整定时任务
        AppPositionPushService.messageHandler(userId, message);
 
    }
 
    @OnClose
    public void onClose(@PathParam("userId") String userId, Session session) {
        //当前的Session 移除
        WebSocketUtils.ONLINE_USER_SESSIONS.remove(userId);
        String message = "用户[" + userId + "] 断开连接!";
        log.info("消息:" + message);
        //从房间中移除用户
        WebSocketUtils.ROOM_USER_SET.values().stream().forEach(userSet -> userSet.remove(userId));
        try {
            session.close();
            AppPositionPushService.stopHandler(userId);
        } catch (IOException e) {
            log.error("onClose error", e);
        }
    }
 
    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            log.error("onError excepiton", e);
        }
        log.info("Throwable msg " + throwable.getMessage());
    }
}