ウェブソケットとは何ですか
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()
},
成功事例図