webSocket使用

项目中用的是vue2,要实现订阅广播以及发送消息的功能。

冷不丁会用几次,记录一下。

首先要下载SockJS、Stomp

npm i sockjs
npm i stompjs -S

然后引用

// import SockJS from "sockjs-client";
import SockJS from 'sockjs-client/dist/sockjs.min.js';
import Stomp from 'stompjs';

第一行引用会报错,会找不到SockJS,所以用第二行的引入方式。

        // ws对接
        getWs() {
            let socket = new SockJS('http://192.xxx.xx.xxx:8080/websocket');
            let stompClient = Stomp.over(socket);
            stompClient.connect(
                { sso_session_id2: localStorage.getItem('Token') },
                frame => {
                    //订阅方法 /topic/project-proposal/chapter-notify/subscribe/{projectId}
                    stompClient.subscribe('/topic/project-proposal/chapter-notify/subscribe/1468036753002942464', function (message) {
                        console.log('订阅 ' + message.body);
                    });
                    //初始化方法 /app/project-proposal/chapter-notify/init/{projectId}
                    stompClient.subscribe('/app/project-proposal/chapter-notify/init/1468036753002942464', function (message) {
                        console.log('初始化 ' + message.body);
                    });
                    //发送消息 /app/project-proposal/chapter-notify/handle/{projectId}
                    /*stompClient.send('/app/project-proposal/chapter-notify/handle/1468036753002942464', {}, "{\"status\":false,\"index\":\"2.1\"}",function (message) {
                console.log('/handle/1468036753002942464: ' + message.body);
            });*/
                    //取消订阅方法 /topic/warn/warning-manage/topic-notify/{projectId}
                    /*stompClient.unsubscribe('/topic/project-proposal/chapter-notify/subscribe/1468036753002942464',{},{},function (message) {
                console.log('/topic/project-proposal/chapter-notify/subscribe/1588433047893921792: ' + message.body);
            });*/
                },
                err => {
                    console.log(err);
                    console.log(err.headers['message']);
                }
            );
        },

调用getWs()方法就好了。

你可能感兴趣的:(websocket,网络协议,网络)