提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.module.infra.websocket; |
H |
2 |
|
|
3 |
import com.iailab.framework.common.enums.UserTypeEnum; |
|
4 |
import com.iailab.framework.websocket.core.listener.WebSocketMessageListener; |
|
5 |
import com.iailab.framework.websocket.core.sender.WebSocketMessageSender; |
|
6 |
import com.iailab.framework.websocket.core.util.WebSocketFrameworkUtils; |
|
7 |
import com.iailab.module.infra.websocket.message.DemoReceiveMessage; |
|
8 |
import com.iailab.module.infra.websocket.message.DemoSendMessage; |
|
9 |
import org.springframework.stereotype.Component; |
|
10 |
import org.springframework.web.socket.WebSocketSession; |
|
11 |
|
|
12 |
import javax.annotation.Resource; |
|
13 |
|
|
14 |
/** |
|
15 |
* WebSocket 示例:单发消息 |
|
16 |
* |
|
17 |
* @author iailab |
|
18 |
*/ |
|
19 |
@Component |
|
20 |
public class DemoWebSocketMessageListener implements WebSocketMessageListener<DemoSendMessage> { |
|
21 |
|
|
22 |
@Resource |
|
23 |
private WebSocketMessageSender webSocketMessageSender; |
|
24 |
|
|
25 |
@Override |
|
26 |
public void onMessage(WebSocketSession session, DemoSendMessage message) { |
|
27 |
Long fromUserId = WebSocketFrameworkUtils.getLoginUserId(session); |
|
28 |
// 情况一:单发 |
|
29 |
if (message.getToUserId() != null) { |
|
30 |
DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(fromUserId) |
|
31 |
.setText(message.getText()).setSingle(true); |
|
32 |
webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), message.getToUserId(), // 给指定用户 |
|
33 |
"demo-message-receive", toMessage); |
|
34 |
return; |
|
35 |
} |
|
36 |
// 情况二:群发 |
|
37 |
DemoReceiveMessage toMessage = new DemoReceiveMessage().setFromUserId(fromUserId) |
|
38 |
.setText(message.getText()).setSingle(false); |
|
39 |
webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), // 给所有用户 |
|
40 |
"demo-message-receive", toMessage); |
|
41 |
} |
|
42 |
|
|
43 |
@Override |
|
44 |
public String getType() { |
|
45 |
return "demo-message-send"; |
|
46 |
} |
|
47 |
|
|
48 |
} |