使用WebSocket进行消息推送(附代码)

 

功能举例: 通过特定操作实时推送到页面反馈进行弹窗和播放音乐。

先贴源代码地址: 点我GO


 

1. 引入pom

创建一个基础的Spring Boot工程(没有特定版本),并在pom.xml中引入需要的依赖内容:

 1       <dependency>
 2             <groupId>org.springframework.boot</groupId>
 3             <artifactId>spring-boot-starter-web</artifactId>
 4         </dependency>
 5 
 6         <dependency>
 7             <groupId>org.springframework.boot</groupId>
 8             <artifactId>spring-boot-starter-freemarker</artifactId>
 9         </dependency>
10 
11         <dependency>
12             <groupId>org.springframework.boot</groupId>
13             <artifactId>spring-boot-starter-websocket</artifactId>
14         </dependency>
15         <dependency>
16             <groupId>org.springframework.boot</groupId>
17             <artifactId>spring-boot-starter-test</artifactId>
18             <scope>test</scope>
19     </dependency>

 

 

 2. 配置配置文件(看需要配置) :

spring.freemarker.template-loader-path=classpath:/templates
spring.mvc.static-path-pattern=/static/**

 

 

 

 3. 在需要接收消息的页面进行配置 :

<script>
    var websocket =null;
    if('WebSocket' in window){
    //这里的地址根据第五步配置的注解地址填写 websocket
= new WebSocket('ws://127.0.0.1:8080/webSocket'); }else { alert('您的浏览器不支持websocket。'); } websocket.onopen = function (event) { console.log('建立连接'); } websocket.onclose = function (event) { console.log('连接关闭'); } websocket.onmessage = function (event) { console.log('收到消息:'+event.data) } websocket.onerror = function () { alert('websocket通信发生错误'); } websocket.onbeforeunload = function(){ websocket.close(); } </script>

 

 


4. 配置WebSocket Bean :

@Component
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointConfigurator(){
        return new ServerEndpointExporter();
    }
}

 


5.实现webSocket

 

@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
    
    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        System.out.println("新的连接 总数:"+webSocketSet.size());
    }


    @OnClose
    public void onColse(){
        webSocketSet.remove(this);
        System.out.println("断开连接 总数:"+webSocketSet.size());

    }

    @OnMessage
    public void onMessage(String message){
        System.out.println("收到客户端发来的消息:"+message);
    }

    public void sendMessage(String message){
        for (WebSocket webSocket : webSocketSet){
            System.out.println("广播消息:"+message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

 

 



6.配置触发控制器

@RequestMapping("/shop")
public class ListController {

    @Autowired
    private WebSocket webSocket;

    /**
     * 接收推送来的消息的页面
     * @return
     */
    @RequestMapping(value ="/list")
    public String list(){
        return "list";
    }

    /**
     * 触发推送
     * 举例:list方法可以是订单列表,这个方法可以是下单的接口,下单后,list的订单列表提示收到新订单。
     * @return
     */
    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(){
        webSocket.sendMessage("hello,来了新数据呢~");
        return "send over,Please return to the list request page。";
    }
}

 



6.配置websocket响应提示:

<audio id="notice" loop="loop">
   <source src="http://fs.w.kugou.com/201905211603/af65d55785b7e97732644d0900fdf8b9/G146/M04/17/18/MocBAFx43JWAdxDBAC92YHGZWaY748.mp3" type="audio/mpeg">
</audio>
websocket.onmessage = function (event) {
        console.log('收到消息:'+event.data)
        alert(event.data);
        var myAuto = document.getElementById('notice');
        console.log('开始播放音乐!15秒后停止...');
        myAuto.play();
        setTimeout(function () {
            myAuto.pause();
            console.log('音乐停止...')
        },15000)
    }


7.测试展示:

请求list地址 http://localhost:8080/shop/list

 

 后台输出:

 


 

触发请求条件: http://localhost:8080/shop/test

 

list页面接收到消息:

 


 

查看:


 

 

 

如有不当之处,请予指正! 如果你有什么疑问也欢迎随时联系我共同探讨。

 

posted @ 2019-05-21 16:50  Timesyys  阅读(2751)  评论(0编辑  收藏  举报