WebSocketService.java
1.38 KB
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
package com.huaheng.framework.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class WebSocketService {
@Autowired
private SimpMessageSendingOperations messaging;
/**
* 发送消息
* @param topic
* @param payload
* @param <T>
*/
public <T> void send(String topic, StompPayload<T> payload) {
List<String> sendTo = payload.getSendTo();
if (sendTo == null) {
//没有指定sendTo则广播发送
sendMessageBroadcast(topic, payload.getData());
} else {
//遍历发送消息给指定用户
for (String loginName : payload.getSendTo()) {
sendMessageToUser(topic, payload.getData(), loginName);
}
}
}
/**
* 广播发送消息
*
* @param topic
* @param data
*/
public <T> void sendMessageBroadcast(String topic, T data) {
messaging.convertAndSend(topic, data);
}
/**
* 给指定用户发消息
*
* @param topic
* @param data
* @param user loginName
*/
public <T> void sendMessageToUser(String topic, T data, String user) {
messaging.convertAndSendToUser(user, topic, data);
}
}