SpringBoot+WebScoket广播

需求:在多个页面中的一个页面发送一个信息,其他的页面都可以收到这个信息。

分析:多个页面连接服务器,在其中的一个页面上输入信息,其他页面可以收到这个信息。

设置端点以及端点的协议

package com.wisely.ch7_6;

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

/**
 * Created by cs on 2017/1/4.
 */
@Configuration
@EnableWebSocketMessageBroker
//开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器Controller支持使用@MessageMapping。就像@RequestMapping
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints (StompEndpointRegistry registry){    //注册一个端点endpoint
        registry.addEndpoint("/endpointWisely").withSockJS();   //指定注册的端点endpointWisely使用SockJS协议
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry){ //配置消息代理(Message Broker)
        registry.enableSimpleBroker("/topic");      //广播式需要配置消息代理,这里配置的是/topic。
    }
}

domian

浏览器向服务器发送消息

package com.wisely.domin;

/**
 * Created by cs on 2017/1/4.
 */
public class WiselyMessage {
    private String name;

    public String getName() {
        return name;
    }
}

服务器向浏览器发送消息

package com.wisely.domin;

/**
 * Created by cs on 2017/1/4.
 */
public class WiselyResponse {
    private String responseMessage;

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

    public String getResponseMessage() {
        return responseMessage;
    }

}

controller

package com.wisely.web;

import com.wisely.domin.WiselyMessage;
import com.wisely.domin.WiselyResponse;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

/**
 * Created by cs on 2017/1/4.
 */
@Controller
public class WsController {
    @MessageMapping("/welcome")     //相当于RequestMapping("/welcome")
    @SendTo("/topic/getResponse")   //当服务端有消息时,会对订阅了@SendTo中的路径的浏览器发送消息
    public WiselyResponse say(WiselyMessage message) throws InterruptedException {
        Thread.sleep(3000);
        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>
    </div>
</div>
<!--
    引入STOMP协议的客户端脚本 stomp.js
    引入SockJS客户端脚本 sockjs.js
    引人jQuery脚本
-->
<script src="//cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<script src="//cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.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';
        $('#response').html();
    }
    
    <!--
        /endpointWisely:上面定义的基于SockJS协议的端点
        二:使用STOMP协议的WebSocket客户端
        三:连接WebScoket服务端
        四:stompClient.subscribe订阅/topic/getResponse目标(destination)发送的消息,这里的
        /topic/getResponse是在控制器的@SendTo中定义的。
        五:stompClient.send向/welcome目标(destination)发送的消息,这里的
        /welcome是在控制器的@MessageMapping中定义的。
    -->
    function connect() {
        var socket = new SockJS('/endpointWisely');
        stompClient = Stomp.over(socket);   //二
        stompClient.connect({},function (frame){ //三
            setConnected(true);
            console.log('Connect:'+frame);
            stompClient.subscribe('/topic/getResponse',function (respnose) {    //四
                showResponse(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",{},JSON.stringify({'name':name}));      //五
    }
    function showResponse(message) {
        var response = $("#response");
        response.html(message);
    }

</script>
</body>
</html>

页面跳转controller

package com.wisely.ch7_6;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by cs on 2017/1/4.
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        //访问路径的方法是/ws,跳向ws.html页面
        registry.addViewController("/ws").setViewName("/ws");
    }
}

效果图:

参考资料:

《JavaEE开发的颠覆者:SpringBoot实战》第七章7.6.3实战

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值