什么时候使用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 @   崛起崛起  阅读(156)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示