I am using web socket using PHP5 and the Chrome browser as client. I have taken the code from the site http://code.google.com/p/phpwebsocket/.
I run the server, and
Finally, I make ws auto reconnect in vue+ts, similar as following:
private async mounted() {
// Connect to WebSocket
const sn = "sb1234567890";
const host =
window.location.protocol == "https:"
? "wss://www.xxx.net"
: process.env.DEV_TYPE === "fullstack"
? "ws://10.0.0.14:8528"
: "ws://www.xxx.net:8528";
const wsUri = host + "/feed-home/" + sn;
await this.startWs(wsUri, sn);
// !!!Deprecated: failed to reconnect
// let ws = new WebSocket();
// console.log(ws);
// ws.onopen = async function(event) {
// console.log(event, "openEvent");
// clearInterval(that.timer);
// };
// ws.onclose = async function(event) {
// console.log(event, "close");
// that.timer = setInterval(() => {
// console.log("Heart Beat");
// ws.send("HeartBeat");
// // ws = new WebSocket("ws://10.0.0.14:8528/feed-home/" + sn);
// console.log(ws);
// }, 60000);
// };
// ws.onmessage = async function(event) {
// console.log(event, "ws");
// alert("get it!");
// await alert("please update!");
// await that.getHome(sn);
// };
}
private wsReconnected: boolean = false; // check whether WebSocket is reconnected
private async startWs(uri: string, sn: string) {
let that = this;
let ws = new WebSocket(uri);
ws.onopen = async () => {
if (that.wsReconnected) {
await that.getHome(sn); // Refresh api data after reconnected
}
ws.send("Current client version: " + window.version);
};
ws.onmessage = async evt => {
await that.getHome(sn);
that.$message({
type: "success",
message: evt.data,
showClose: true,
center: true,
duration: 20 * 1000
});
};
ws.onclose = async () => {
that.wsReconnected = true;
await that.startWs(uri, sn);
const sleep = (seconds: number) => {
return new Promise(resolve =>
setTimeout(resolve, seconds * 1000)
);
};
await sleep(10); // Try to reconnect in 10 seconds
// !!!Deprecated: Use timer will cause multiply ws connections
// if (!that.wsTimer) {
// // Try to reconnect in 10 seconds
// that.wsTimer = setInterval(async () => {
// console.log("reconnecting websocket...");
// await that.startWs(uri, sn);
// }, 10 * 1000);
// }
};
}
GitHub hosts a small JavaScript library that decorates the WebSocket API to provide a WebSocket connection that will automatically reconnect if the connection is dropped.
Minified library with gzip compression is less than 600 bytes.
The official repository is available here:
https://github.com/joewalnes/reconnecting-websocket
If a high number of clients are connected to the server when it reboots. It may be worthwhile to manage the reconnect timings of the clients by using an Exponential Backoff algorithm.
The algorithm works like this:
Référence:
http://blog.johnryding.com/post/78544969349/how-to-reconnect-web-sockets-in-a-realtime-web-app
ReconnectingWebSocket does not handle reconnections by using this algorithm.
Below are the codes i have used in my project which working 100%.
var name = sessionStorage.getItem('name');
wsUri = "ws://localhost:8080";
var websocket;
$(function() {
init();
$("#chat_text_box").on("keypress", function(e) {
if (e.keyCode == 13) { //For Enter Button
e.preventDefault();
var mymessage = $('#chat_text_box').val();
if(mymessage){
var msg = { type: 'chat_text', data : { name:name, msg:mymessage } };
console.log(msg);
websocket.send(JSON.stringify(msg));
$('#chat_text_box').val('');
}
return false;
}
});
});
function init() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(ev) { /*connection is open */ }
websocket.onmessage = function(ev) {
var data = JSON.parse(ev.data); //PHP sends Json data
var type = data.type;//alert(JSON.stringify(data));
switch(type) {
case "chat_text":
var text = "<div><span class='user'>"+data.data.sender_name+" : </span><span class='msg'>"+data.data.msg+"</span></div>";
$('#chat-messages').append(text);
break;
default:
break;
}
};
websocket.onerror = function(ev){};
websocket.onclose = function(ev) { init(); };
}