什么是websocket
1, WebSocket是一种用于在客户端和服务器之间进行全双工通信的网络协议。它使得在单个TCP连接上可以进行双向通信,允许服务器主动地发送数据给客户端,同时客户端也可以向服务器发送数据。与传统的HTTP请求-响应模型不同,WebSocket允许实时通信,从而可以支持实时更新的应用程序,如即时聊天、在线游戏和股票市场报价。
2,WebSocket协议通过建立持久化的连接,避免了HTTP请求的额外开销和延迟。客户端可以使用WebSocket API与服务器建立连接,并通过发送和接收消息进行通信。WebSocket还支持一些高级功能,如心跳检测、数据压缩和扩展。
3,本文是在可视化数据大屏中使用进行的一些操作
data ( ) {
return {
websocket : { } ,
websocketUrl : 'ws://192.168.1.14:2000/' ,
lockReconnect : false ,
}
}
webScoketInit ( ) {
var that = this ;
that. websocket = new WebSocket ( that. websocketUrl) ;
that. websocket. onerror = function ( event ) {
reconnect ( that. websocketUrl) ;
console. log ( event) ;
console. log ( '连接错误' )
} ;
that. websocket. onopen = function ( event ) {
heartCheck. reset ( ) . start ( ) ;
console. log ( event, '成功数据' ) ;
console. log ( '连接开启' )
}
that. websocket. onmessage = function ( event ) {
let res = event. data
console. log ( res, '==============websocks' )
if ( res== "reload" ) {
that. websk ( )
}
heartCheck. reset ( ) . start ( ) ;
}
that. websocket. onclose = function ( event ) {
reconnect ( that. websocketUrl) ;
console. log ( event) ;
console. log ( '连接关闭' )
}
window. onbeforeunload = function ( ) {
closeWebSocket ( ) ;
}
function reconnect ( url ) {
if ( that. lockReconnect) return ;
that. lockReconnect = true ;
setTimeout ( function ( ) {
that. webScoketInit ( ) ;
that. lockReconnect = false ;
console. log ( '重连中' )
} , 2000 ) ;
}
var heartCheck = {
timeout : 1000 ,
timeoutObj : null ,
serverTimeoutObj : null ,
reset : function ( ) {
clearTimeout ( this . timeoutObj) ;
clearTimeout ( this . serverTimeoutObj) ;
return this ;
} ,
start : function ( ) {
var self = this ;
this . timeoutObj = setTimeout ( function ( ) {
that. websocket. send ( "ping" ) ;
self. serverTimeoutObj = setTimeout ( function ( ) {
console. log ( '重新连接' )
that. websocket. close ( ) ;
} , self. timeout)
} , this . timeout)
}
}
function closeWebSocket ( ) {
that. websocket. close ( ) ;
}
} ,
websk ( ) {
window. location. reload ( )
} ,
成功示例图