springboot整合websocket實現一對一訊息推送和廣播訊息推送

NO IMAGE
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

springboot基礎環境,請參考springboot文件
maven依賴

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

程式碼準備

準備常量類

//webSocket相關配置
//連結地址
public static String WEBSOCKETPATHPERFIX = "/ws-push";
public static String WEBSOCKETPATH = "/endpointWisely";
//訊息代理路徑
public static String WEBSOCKETBROADCASTPATH = "/topic";
//前端傳送給服務端請求地址
public static final String FORETOSERVERPATH = "/welcome";
//服務端生產地址,客戶端訂閱此地址以接收服務端生產的訊息
public static final String PRODUCERPATH = "/topic/getResponse";
//點對點訊息推送地址字首
public static final String P2PPUSHBASEPATH = "/user";
//點對點訊息推送地址字尾,最後的地址為/user/使用者識別碼/msg
public static final String P2PPUSHPATH = "/msg";

接收前端訊息實體

public class WiselyMessage {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
後臺傳送訊息實體

private String responseMessage;

public WiselyResponse(String responseMessage){
    this.responseMessage = responseMessage;
}

public String getResponseMessage() {
    return responseMessage;
}

public void setResponseMessage(String responseMessage) {
    this.responseMessage = responseMessage;
}

配置websocket

@Configuration
// @EnableWebSocketMessageBroker註解用於開啟使用STOMP協議來傳輸基於代理(MessageBroker)的訊息,這時候控制器(controller)開始支援@MessageMapping,就像是使用@requestMapping一樣。
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
    //註冊一個Stomp的節點(endpoint),並指定使用SockJS協議。
        stompEndpointRegistry.addEndpoint(Constant.WEBSOCKETPATH).withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //服務端傳送訊息給客戶端的域,多個用逗號隔開
        registry.enableSimpleBroker(Constant.WEBSOCKETBROADCASTPATH, Constant.P2PPUSHBASEPATH);
        //定義一對一推送的時候字首
        registry.setUserDestinationPrefix(Constant.P2PPUSHBASEPATH);
        //定義websoket字首
        registry.setApplicationDestinationPrefixes(Constant.WEBSOCKETPATHPERFIX);
    }
}

service

@Service
public class WebSocketService {

    @Autowired
    private SimpMessagingTemplate template;

    /**
     * 廣播
     * 發給所有線上使用者
     * @param msg
     */
    public void sendMsg(WiselyResponse msg) {
        template.convertAndSend(Constant.PRODUCERPATH, msg);
    }

    /**
     * 傳送給指定使用者
     * @param users
     * @param msg
     */
    public void send2Users(List<String> users, WiselyResponse msg) {
        users.forEach(userName -> {
            template.convertAndSendToUser(userName, Constant.P2PPUSHPATH, msg);
        });
    }
}

控制器

@Controller
public class WsController {
    @Resource
    WebSocketService webSocketService;
    @MessageMapping(Constant.FORETOSERVERPATH)//@MessageMapping和@RequestMapping功能類似,用於設定URL對映地址,瀏覽器向伺服器發起請求,需要通過該地址。
    @SendTo(Constant.PRODUCERPATH)//如果伺服器接受到了訊息,就會對訂閱了@SendTo括號中的地址傳送訊息。
    public WiselyResponse say(WiselyMessage message) throws Exception {
        List<String> users = Lists.newArrayList();
        users.add("d892bf12bf7d11e793b69c5c8e6f60fb");//此處寫死只是為了方便測試,此值需要對應頁面中訂閱個人訊息的userId
        webSocketService.send2Users(users, new WiselyResponse("admin hello"));

        return new WiselyResponse("Welcome, "   message.getName()   "!");
    }
}

頁面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Boot WebSocket 廣播式</title>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">貌似你的瀏覽器不支援websocket</h2>          </noscript>
<div>
<div>
    <button id="connect" onclick="connect();">連線</button>
    <button id="disconnect" disabled="disabled" onclick="disconnect();">斷開連線</button>
</div>
<div id="conversationDiv">
    <label>輸入你的名字</label><input type="text" id="name" />
    <button id="sendName" onclick="sendName();">傳送</button>
    <p id="response"></p>
    <p id="response1"></p>
</div>
</div>
<!--<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>-->
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js">    </script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>      
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script th:inline="javascript">
var stompClient = null;
//此值有服務端傳遞給前端,實現方式沒有要求
var userId = [[${userId}]];

function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
    $('#response').html();
}

function connect() {
    var socket = new SockJS('/endpointWisely'); //1連線SockJS的endpoint是“endpointWisely”,與後臺程式碼中註冊的endpoint要一樣。
    stompClient = Stomp.over(socket);//2建立STOMP協議的webSocket客戶端。
    stompClient.connect({}, function(frame) {//3連線webSocket的服務端。
        setConnected(true);
        console.log('開始進行連線Connected: '   frame);
        //4通過stompClient.subscribe()訂閱伺服器的目標是'/topic/getResponse'傳送過來的地址,與@SendTo中的地址對應。
        stompClient.subscribe('/topic/getResponse', function(respnose){
            showResponse(JSON.parse(respnose.body).responseMessage);
        });
        //4通過stompClient.subscribe()訂閱伺服器的目標是'/user/'   userId   '/msg'接收一對一的推送訊息,其中userId由服務端傳遞過來,用於表示唯一的使用者,通過此值將訊息精確推送給一個使用者
        stompClient.subscribe('/user/'   userId   '/msg', function(respnose){
            console.log(respnose);
            showResponse1(JSON.parse(respnose.body).responseMessage);
        });
    });
}


function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    var name = $('#name').val();
    //通過stompClient.send()向地址為"/welcome"的伺服器地址發起請求,與@MessageMapping裡的地址對應。因為我們配置了registry.setApplicationDestinationPrefixes(Constant.WEBSOCKETPATHPERFIX);所以需要增加字首/ws-push/
    stompClient.send("/ws-push/welcome", {}, JSON.stringify({ 'name': name }));
}

function showResponse(message) {
    var response = $("#response");
    response.html(message);
}
function showResponse1(message) {
    var response = $("#response1");
    response.html(message);
}
</script>
</body>
</html>

測試

點選連線控制檯輸出

表示連線成功並且訂閱了兩個地址

此時在文字框內輸入任意值
結果如圖所示則代表成功

控制檯中顯示依次為,傳送資訊,目標長度內容

此時服務端控制器接收到請求

同時給指定使用者傳送了訊息,所以控制檯接收到訊息

同時因為控制器有註解@SendTo所以會向@SendTo的地址廣播訊息,客戶端訂閱了廣播地址所有控制檯顯示接收了訊息

相關文章

開發語言 最新文章