前端WebSocket进行消息实时推送和提示(附代码)

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

先贴源代码地址: 点我GO


  • 引入pom

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

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

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

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

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

  •   配置配置文件(看需要配置) :
spring.freemarker.template-loader-path=classpath:/templates
spring.mvc.static-path-pattern=/static/**

  •  在需要接收消息的页面进行配置 :
<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>

  • 配置WebSocket Bean :
@Component
public class WebSocketConfig {

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

  • 实现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();
            }

        }
    }
}

  • 配置触发控制器
@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。";
    }
}

  • 配置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)
    }

  • 测试展示:

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

 后台输出:

扫描二维码关注公众号,回复: 10211812 查看本文章

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

list页面接收到消息:


查看:


 

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

Email:wdnnccey#gmail.com

你配不上自己的野心 也辜负了所受的苦难

发布了79 篇原创文章 · 获赞 276 · 访问量 57万+

猜你喜欢

转载自blog.csdn.net/alan_liuyue/article/details/103419332