Vue使用WebSocket实现在线聊天

1.判断浏览器是否支持WebSocket,发起WebSocket连接

if(typeof(WebSocket) === 'undefined'){
    alert("您的浏览器不支持在线聊天")
}else{
    //初始化WebSocket
    _this.socket = new WebSocket("wss://"+你的地址)
    _this.socket.onopen = function(){
			console.log("连接成功")
			heartCheck.reset().start()
	}
}

2.增加心跳检测,并在WebSocket连接成功是调用该方法

                        let _this = this
						var heartCheck = {
							timeout:5000,
							timeoutObj:null,
							reset:function(){
								clearInterval(this.timeoutObj)
								return this;
							},
							start:function(){
								this.timeoutObj = setInterval(function(){
									_this.socket.send('heartbeat')
									console.log("给服务器发送:heartbeat")
								},this.timeout)
							}
						}

3.接收到服务器的消息

_this.socket.onmessage = function(event){
    console.log("接收到服务器消息:"+event.data)
}

4.关闭时聊天时销毁WebSocket链接

this.socket.close()

完整代码

    init(){
    if(typeof(WebSocket) === 'undefined'){
						alert("您的浏览器不支持在线聊天")
					}else{
						let _this = this
						var heartCheck = {
							timeout:5000,
							timeoutObj:null,
							reset:function(){
								clearInterval(this.timeoutObj)
								return this;
							},
							start:function(){
								this.timeoutObj = setInterval(function(){
									_this.socket.send('heartbeat')
									console.log("给服务器发送:heartbeat")
								},this.timeout)
							}
						}
						_this.socket = new WebSocket("wss://" + )
						_this.socket.onopen = function(){
							console.log("连接成功")
							heartCheck.reset().start()
						}
						_this.socket.onmessage = function(event){
							console.log("接收到服务器消息:"+event.data)
					
						}
					}
}

猜你喜欢

转载自blog.csdn.net/m0_61570521/article/details/123281522
今日推荐