ZQN
2024-06-17 b1ff19545212508d3f65741ab889f0b6df82a511
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
118
119
120
121
122
123
124
125
126
127
package com.project.scoket;
 
 
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.common.core.domain.entity.SysUser;
import com.project.common.exception.base.BaseException;
import com.project.common.utils.JsonUtils;
import com.project.common.utils.StringUtils;
import com.project.common.utils.spring.SpringUtils;
import com.project.system.mapper.SysUserMapper;
import com.project.util.CurPoolUtil;
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.util.Date;
import java.util.Map;
 
import static com.project.util.CurPoolUtil.webSockets;
 
 
@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}/{toUserId}")
public class WebSocket {
 
 
    private Session session;
 
 
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId, @PathParam(value = "toUserId") String toUserId)
    {
        this.session = session;
        webSockets.put(Long.parseLong(userId),this);
        CurPoolUtil.sessionPool.put(Long.parseLong(userId) , session);
 
 
        log.info("【websocket消息】有新的连接,userId:"+userId+", toUserId:"+toUserId+", 总数为:"+ webSockets.size());
        System.out.println("【websocket消息】有新的连接,userId:"+userId+", toUserId:"+toUserId+", 总数为:"+ webSockets.size());
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose()
    {
        // 断开连接删除用户删除session
        Long userId = Long.parseLong(this.session.getRequestParameterMap().get("userId").get(0));
        CurPoolUtil.sessionPool.remove(userId);
        webSockets.remove(userId);
        SysUserMapper userMapper = SpringUtils.getBean(SysUserMapper.class);
        SysUser sysUser = userMapper.selectUserById(userId);
        CurPoolUtil.curUserPool.remove(sysUser.getUserName());
        System.out.println("【websocket消息】连接断开,usserId:"+userId+",总数为:"+ webSockets.size());
    }
 
    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message,@PathParam(value = "userId") String userId, @PathParam(value = "toUserId") String toUserId)
    {
        if ("0".equals(toUserId)){
            log.info("toUserId------------>"+toUserId+",不能发送消息");
            throw new BaseException("不能发送消息");
        }
 
    }
 
    @OnError
    public void onError(Session session, Throwable error)
    {
        log.error("发生错误");
        error.printStackTrace();
    }
 
 
    // 广播消息
    public void sendAllMessage(String message)
    {
        Map<Long, WebSocket> sockets = webSockets;
        if (StringUtils.isNotEmpty(sockets)){
            for (Long aLong : sockets.keySet()) {
                try {
                    WebSocket webSocket = webSockets.get(aLong);
                    if (webSocket.session!=null){
                        webSocket.session.getAsyncRemote().sendText(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
 
        }
    }
 
 
    // 单点消息 (发送文本)
    public void sendTextMessage(Long userId, String message)
    {
        Session session = (Session) CurPoolUtil.sessionPool.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("【websocket发送消息】接收者:"+userId+",消息:"+message);
        System.out.println("【session】session:"+session);
        log.info("【websocket发送消息】接收者:"+userId+",消息:"+message);
    }
 
 
 
}