SpringBoot + webSocket + stomp +thymeleaf 推流

2021-03-05 20:30

阅读:619

YPE >

/strong> html>

xmlns:th="http://www.thymeleaf.org">

     charset="UTF-8" />

    Spring Boot+WebSocket+广播式(点对点)

   

onload="disconnect()">

style="color: #ff0000">貌似你的浏览器不支持websocket

    

        

        

        

   

    

    

id="conversationDiv">

        输入你的信息 type="text" id="name" />

        

        

id="response">

    

    var stompClient = null;

   

    function setConnected(flag) {

        // document.getElementById(‘connect‘).disabled = flag;

        document.getElementById(‘disconnect‘).disabled = !flag;

        document.getElementById(‘conversationDiv‘).style.visibility = flag ? ‘visible‘ : ‘hidden‘;

    }

   

         

    function serverReturnMessage() {

        //若前后端分离,url要写全,若在一个项目内,只写/websocket/server就行

        var url = "http://ip:8080/websocket/server"

        var socket = new SockJS(url); //链接SockJS 的endpoint 名称为后台声明的"/websocket/server"

        stompClient = Stomp.over(socket);//使用stomp子协议的WebSocket 客户端

        stompClient.connect({}, function(frame) {//链接Web Socket的服务端。

            setConnected(true);

            console.log(‘Connected: ‘ + frame);

            //广播式发送,订阅地址不需要加唯一标识;点对点发送,可自定义唯一标识

            var subUrl= ‘/topic/serverReturnMessage‘;

            stompClient.subscribe(subUrl, function(respnose){ //订阅/topic/getResponse 目标发送的消息。这个是在控制器的@SendTo中定义的。

                showResponse(JSON.parse(respnose.body).name);

            });

        });

    }

   

    //断开连接

    function disconnect() {

        if (stompClient != null) {

            stompClient.disconnect();

        }

        setConnected(false);

        console.log("Disconnected");

    }

   

    function showResponse(message) {

        var response = $("#response");

        console.log(message);

    }

//向stompClient发送请求

    function sendName() {

        var name = $(‘#name‘).val();

        //通过stompClient.send 向/welcome 目标 发送消息,这个是在控制器的@messageMapping 中定义的。

        //在这里,可根据业务自定义json,甚至可以把订阅地址的唯一标识在此传入给后台解析

        var obj = JSON.stringify({‘name‘: name, ‘retailmId‘: ‘001‘})

   

        stompClient.send("/sendTest", {}, obj);

    }


评论


亲,登录后才可以留言!