houzhongyi
2024-07-11 e7c1260db32209a078a962aaa0ad5492c35774fb
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
package com.iailab.module.infra.websocket;
 
import com.iailab.framework.common.enums.UserTypeEnum;
import com.iailab.framework.websocket.core.listener.WebSocketMessageListener;
import com.iailab.framework.websocket.core.sender.WebSocketMessageSender;
import com.iailab.framework.websocket.core.util.WebSocketFrameworkUtils;
import com.iailab.module.infra.websocket.message.DemoReceiveMessage;
import com.iailab.module.infra.websocket.message.DemoSendMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
 
import javax.annotation.Resource;
 
/**
 * WebSocket 示例:单发消息
 *
 * @author iailab
 */
@Component
public class DemoWebSocketMessageListener implements WebSocketMessageListener<DemoSendMessage> {
 
    @Resource
    private WebSocketMessageSender webSocketMessageSender;
 
    @Override
    public void onMessage(WebSocketSession session, DemoSendMessage message) {
        Long fromUserId = WebSocketFrameworkUtils.getLoginUserId(session);
        // 情况一:单发
        if (message.getToUserId() != null) {
            DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(fromUserId)
                    .setText(message.getText()).setSingle(true);
            webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), message.getToUserId(), // 给指定用户
                    "demo-message-receive", toMessage);
            return;
        }
        // 情况二:群发
        DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(fromUserId)
                .setText(message.getText()).setSingle(false);
        webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), // 给所有用户
                "demo-message-receive", toMessage);
    }
 
    @Override
    public String getType() {
        return "demo-message-send";
    }
 
}