什么时候使用websocket(即时通讯)

websocket的用途

用于多个用户相互交流

用于展示服务器端经常变动的数据

websocket和http的区别

http只能是客户端向服务器发出请求,服务器返回查询结果。HTTP 协议做不到服务器主动向客户端推送信息。

websocket服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。

websocket的使用

      init: function () {
            console.log("初始化ws")
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(this.path)
                // 监听socket连接
                this.socket.onopen = this.open
                // 监听socket错误信息
                this.socket.onerror = this.error
                // 监听socket消息
                this.socket.onmessage = this.getMessage
            }
        },
        open: function () {
            console.log("socket连接成功")
            this.send();
        },
        error: function (err) {
            console.log("连接错误",err)
        },
        getMessage: function (msg) {
            console.log(msg)
            this.msgCount = JSON.parse(msg.data).noHandleCount;
        },
        send: function () {
            console.log("发送消息")
            let data = {
                handlePeople:JSON.parse(localStorage.getItem('user')).staffAccount
            }
            this.socket.send(JSON.stringify(data))
        },
        close: function () {
            console.log("socket已经关闭")
        },
 path:"wss://"+ window.location.host +"/ws",
 
posted @ 2022-10-08 11:50  崛起崛起  阅读(162)  评论(0)    收藏  举报