Use of vue socket

1, a brief introduction

There are library-based webSocket communication socket.io , SockJS , this time with SockJS.

2, provided

Here we use sockjs-Client , stomjs these two modules to achieve webSocket communication needs with the background, use the corresponding module.

Client-sockjs
sockjs-Client is separated from SockJS communication module for clients to use. So we just look at SockJS. SockJS is a browser JavaScript library that provides an object similar to a network, SockJS provide a coherent, cross-browser JavaScriptAPI, it creates a low latency, full-duplex, cross-domain communication channel between the browser and the Web server. you might ask, why not just use native WebSocket Instead, use SockJS it? thanks a major feature of SockJS, some browsers lack support for WebSocket, so the fallback option is necessary, and based on the Spring framework provides transparent fallback option SockJS agreement. SockJS provides browser compatibility, native WebSocket precedence, if a browser does not support WebSocket, SockJS automatically downgraded to a poll.

stomjs
the STOMP (the Text-Orientated the Simple Messaging Protocol) protocol message, a simple text-oriented;
a WebSocket is a messaging architecture, does not force any particular message protocol, meaning it depends on the application layer to decipher the message.
unlike HTTP, is in a WebSocket a very thin layer over TCP, will byte stream into text / binary message, therefore, for practical applications, the communication format WebSocket low level, and therefore, can be used on top of WebSocket STOMP protocol, is to browse increase the amount of communication between the message semantics and server.

STOMP and WebSocket relationship:

  1. HTTP protocol solves the web browser to initiate a request and the details of the web server responds to the request, assuming the HTTP protocol does not exist, can only use TCP sockets to write web applications, you might think this is a crazy thing;
  2. Direct use WebSocket (SockJS) is very similar to using TCP sockets to write web applications, because there is no high-level protocol, it is necessary to send a message semantics between application we define, also need to ensure that both ends of the connection can follow these semantics;
  3. In addition request on TCP sockets with HTTP - the same response model layer, STOMP provides a frame format based on the line layer WebSocket, used to define the semantics of the message.

3, Code

Install sockjs-client and stompjs

npm install sockjs-client
npm install stompjs
import SockJS from  'sockjs-client';
import  Stomp from 'stompjs';
export default {
    data(){
        return {
            stompClient:'',
            timer:'',
        }
    },
    methods:{
        initWebSocket() {
            this.connection();
            let that= this;
            // 断开重连机制,尝试发送消息,捕获异常发生时重连
            this.timer = setInterval(() => {
                try {
                    that.stompClient.send("test");
                } catch (err) {
                    console.log("断线了: " + err);
                    that.connection();
                }
            }, 5000);
        },  
        connection() {
            // 建立连接对象
            let socket = new SockJS('http://10.10.91.4:8081/ws');
            // 获取STOMP子协议的客户端对象
            this.stompClient = Stomp.over(socket);
            // 定义客户端的认证信息,按需求配置
            let headers = {
                Authorization:''
            }
            // 向服务器发起websocket连接
            this.stompClient.connect(headers,() => {
                this.stompClient.subscribe('/topic/public', (msg) => { // 订阅服务端提供的某个topic
                    console.log('广播成功')
                    console.log(msg);  // msg.body存放的是服务端发送给我们的信息
                },headers);
                this.stompClient.send("/app/chat.addUser",
                    headers,
                    JSON.stringify({sender: '',chatType: 'JOIN'}),
                )   //用户加入接口
            }, (err) => {
                // 连接发生错误时的处理函数
                console.log('失败')
                console.log(err);
            });
        },    //连接 后台
        disconnect() {
            if (this.stompClient) {
                this.stompClient.disconnect();
            }
        },  // 断开连接
    },
    mounted(){
        this.initWebSocket();
    },
    beforeDestroy: function () {
        // 页面离开时断开连接,清除定时器
        this.disconnect();
        clearInterval(this.timer);
    }
}

Reference article https://juejin.im/post/5b7fd02d6fb9a01a196f6276

Published 177 original articles · won praise 18 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_38331049/article/details/105224134