websocket:支持 前端连接 + 订阅

要实现的功能:后端提供 可订阅的数据,前端连接成功后 订阅后 定时被推送数据。

---直接上代码---

websocket配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //添加一个/websocket端点,客户端就可以通过这个端点来进行连接;withSockJS作用是添加SockJS支持
        registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //定义了两个客户端订阅地址的前缀信息,也就是客户端接收服务端发送消息的前缀信息
        registry.enableSimpleBroker("/topic","/queue");
        //定义了服务端接收地址的前缀,也即客户端给服务端发消息的地址前缀
        registry.setApplicationDestinationPrefixes("/app");
    }
​​​​​​​}

定时任务 提供订阅数据

//定时任务发布消息(每十秒执行一次)
    @Scheduled(cron = "*/10 * * * * ?")//运行周期时间可配
    public void publicMarketValueMessage() {
        //这里的nowDate 暂且作为订阅的内容--可更换为具体的业务数据
        String nowDate = dateFormat.format(new Date());
        //这里的destination 是 订阅的地址
        String destination = "/topic/echoTest/price";
        log.info("websocket 【{}】定时任务发布消息==>【开始】", destination);
        try {
            this.template.convertAndSend(destination, nowDate);
        }catch (Exception e){
            log.error("websocket ={} 定时任务发布消息==>【异常】", destination, e);
        }
    }

前端测试代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script type="text/javascript"> 

    var stompClient = null;  

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

    function connect() {  
        var socket = new SockJS('https://localhost:8080/websocket');//连接服务端的端点,连接以后才可以订阅广播消息和个人消息 
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {  
            setConnected(true);  
            console.log('Connected: ' + frame); 
            //订阅广播消息
            stompClient.subscribe('/topic/echoTest/price', function(greeting){  
                showGreeting(greeting.body);  
            });
        });  
    }

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

    function showGreeting(message) {  
        var response = document.getElementById('response');  
        var p = document.createElement('p');  
        p.style.wordWrap = 'break-word';  
        p.appendChild(document.createTextNode(message));  
        response.appendChild(p);  
    }

</script>
</head>
<body class="easyui-layout">
    <div>  
        <div>  
            <button id="connect" onclick="connect();">Connect</button>  
            <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>  
        </div>  
        <div id="conversationDiv">  
            <p id="response" style="border: black;width: 500px;border-style: dashed;"></p>  
        </div>  
    </div> 


</body>
</html>

--如有问题欢迎沟通 交流--

 

 

 

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值