WebSocketService.java 1.38 KB
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);
    }
}