springboot websocket stompjs socketjs 按主题订阅

package com.example.lesson1.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{

    public void configureMessageBroker(MessageBrokerRegistry config){
        config.enableSimpleBroker("/topic");
//        config.setApplicationDestinationPrefixes("/app");
    }

    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/webServer").withSockJS();
    }

}

 

 

package com.example.lesson1.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WebSocketController {

    @Autowired
    public SimpMessagingTemplate simpMessagingTemplate;

    @RequestMapping("/websocket")
    public ModelAndView websocket(){
        return new ModelAndView("websocket");
    }

    @MessageMapping("/subscribe")
    @SendTo("/topic/getResponse/{topicId}")
    public String subscribe(@PathVariable int topicId) {
        return "服务器发送消息"+topicId;
    }

    @SubscribeMapping("/topic/getResponse/{topicId}")
    public String sub2112(@DestinationVariable int topicId) {
        return "初始化订阅消息"+topicId;
    }

    @GetMapping("/serverMessage")
    @ResponseBody
    public void serverMessage() throws InterruptedException {

        while(true){

            simpMessagingTemplate.convertAndSend("/topic/getResponse/1","服务器端消息1");
            simpMessagingTemplate.convertAndSend("/topic/getResponse/0","服务器端消息0");
            Thread.sleep(1000);
        }


    }

}
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello topic</title>

</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div>
    <div>
        <button id="connect" οnclick="connect();">Connect</button>
        <button id="disconnect"  οnclick="disconnect();">Disconnect</button>
        <button id="unsubscribe"  οnclick="unsubscribe();">unsubscribe</button>
        <button id="resubscribe"  οnclick="resubscribe();">resubscribe</button>
    </div>
    <div id="conversationDiv">
        <labal>名字</labal><input type="text" id="name" />
        <button id="sendName" οnclick="sendName();">Send</button>
        <p id="response"></p>
    </div>
</div>

<script src="https://cdn.bootcss.com/sockjs-client/1.3.0/sockjs.min.js" ></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js" ></script>

<script type="text/javascript">
    var stompClient = null;
    function connect() {
        var socket = new SockJS("/spring-boot-vue/webServer");
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {

            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/getResponse/0', function(response){
                var response1 = document.getElementById('response');
                var p = document.createElement('p');
                p.style.wordWrap = 'break-word';
                p.appendChild(document.createTextNode(response.body));
                response1.appendChild(p);
            });
        });
    }

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

    function unsubscribe() {

        console.log(stompClient.subscriptions);

        for (var sub in stompClient.subscriptions) {
            if (stompClient.subscriptions.hasOwnProperty(sub)) {
                stompClient.unsubscribe(sub);
            }
        }
    }

    function resubscribe(){
        stompClient.subscribe('/topic/getResponse/1', function(response){
            var response1 = document.getElementById('response');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.appendChild(document.createTextNode(response.body));
            response1.appendChild(p);
        });
    }

    function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("/subscribe", {}, JSON.stringify({ 'name': name }));
    }
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值