我正在使用使用 PHP5 和 Chrome 浏览器作为客户端的 Web 套接字。我已从网站http://code.google.com/p/phpwebsocket/获取代码。
我运行服务器,客户端也已连接。我也可以聊天。现在,当我重新启动服务器(通过杀死它并再次启动它)时,客户端会获取断开连接的信息,但在我发送消息时不会自动重新连接服务器。
如何做到这一点?就像当我得到断开连接的信息时,我应该检查它并将其发送到 JavaScript 以刷新页面还是重新连接?
我正在使用使用 PHP5 和 Chrome 浏览器作为客户端的 Web 套接字。我已从网站http://code.google.com/p/phpwebsocket/获取代码。
我运行服务器,客户端也已连接。我也可以聊天。现在,当我重新启动服务器(通过杀死它并再次启动它)时,客户端会获取断开连接的信息,但在我发送消息时不会自动重新连接服务器。
如何做到这一点?就像当我得到断开连接的信息时,我应该检查它并将其发送到 JavaScript 以刷新页面还是重新连接?
当服务器重新启动时,Web Socket 连接关闭,因此onclose
触发了 JavaScript 事件。这是一个尝试每五秒重新连接一次的示例。
function start(websocketServerLocation){
ws = new WebSocket(websocketServerLocation);
ws.onmessage = function(evt) { alert('message received'); };
ws.onclose = function(){
// Try to reconnect in 5 seconds
setTimeout(function(){start(websocketServerLocation)}, 5000);
};
}
Andrew 给出的解决方案并不完美,因为在失去连接的情况下,服务器可能会发送几个关闭事件。
在这种情况下,您将设置几个 setTimout。Andrew 给出的解决方案可能只有在服务器在五秒之前准备好时才有效。
然后,基于 Andrew 解决方案,重新设计,我利用 setInterval 将 ID 附加到窗口对象(这样它“无处不在”):
var timerID=0;
var socket;
/* Initiate what has to be done */
socket.onopen=function(event){
/* As what was before */
if(window.timerID){ /* a setInterval has been fired */
window.clearInterval(window.timerID);
window.timerID=0;
}
/* ... */
}
socket.onclose=function(event){
/* ... */
if(!window.timerID){ /* Avoid firing a new setInterval, after one has been done */
window.timerID=setInterval(function(){start(websocketServerLocation)}, 5000);
}
/* That way, setInterval will be fired only once after losing connection */
/* ... */
}
有一个小的 JavaScript 库装饰 WebSocket API 以提供 WebSocket 连接,如果连接断开,该连接将自动重新连接。
使用 gzip 压缩的缩小库小于 600 字节。
该存储库可在此处获得:
https://github.com/joewalnes/reconnecting-websocket
还有一个 TypeScript 库。只需包含它并替换new WebSocket
为new ReconnectingWebSocket
.
该存储库可在此处获得:
https://github.com/pladaria/reconnecting-websocket
如果大量客户端在重新启动时连接到服务器。通过使用指数退避算法来管理客户端的重新连接时间可能是值得的。
该算法的工作原理如下:
参考:
http://blog.johnryding.com/post/78544969349/how-to-reconnect-web-sockets-in-a-realtime-web-app
ReconnectingWebSocket 不使用此算法处理重新连接。
我已经将这个模式用于纯香草 JavaScript 一段时间了,它支持的情况比其他答案多一些。
document.addEventListener("DOMContentLoaded", function() {
'use strict';
var ws = null;
function start(){
ws = new WebSocket("ws://localhost/");
ws.onopen = function(){
console.log('connected!');
};
ws.onmessage = function(e){
console.log(e.data);
};
ws.onclose = function(){
console.log('closed!');
//reconnect now
check();
};
}
function check(){
if(!ws || ws.readyState == 3) start();
}
start();
setInterval(check, 5000);
});
这将在服务器关闭连接后立即重试,并且它会检查连接以确保它也每 5 秒启动一次。
因此,如果服务器在运行时或在 onclose 事件发生时未启动,则连接仍会在重新联机后恢复。
注意:使用此脚本不会让您停止尝试打开连接...但我认为这就是您想要的吗?
以下是我在项目中使用的 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(); };
}
无法评论,但以下内容:
var socket;
const socketMessageListener = (event) => {
console.log(event.data);
};
const socketOpenListener = (event) => {
console.log('Connected');
socket.send('hello');
};
const socketCloseListener = (event) => {
if (socket) {
console.error('Disconnected.');
}
socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', socketOpenListener);
socket.addEventListener('message', socketMessageListener);
socket.addEventListener('close', socketCloseListener);
};
socketCloseListener();
// for testing
setTimeout(()=>{
socket.close();
},5000);
加上https://www.npmjs.com/package/back已经足够好了 :)
function wsConnection(url){
var ws = new WebSocket(url);
var s = (l)=>console.log(l);
ws.onopen = m=>s(" CONNECTED")
ws.onmessage = m=>s(" RECEIVED: "+JSON.parse(m.data))
ws.onerror = e=>s(" ERROR")
ws.onclose = e=>{
s(" CONNECTION CLOSED");
setTimeout((function() {
var ws2 = new WebSocket(ws.url);
ws2.onopen=ws.onopen;
ws2.onmessage = ws.onmessage;
ws2.onclose = ws.onclose;
ws2.onerror = ws.onerror;
ws = ws2
}
).bind(this), 5000)
}
var f = m=>ws.send(JSON.stringify(m)) || "Sent: "+m;
f.ping = ()=>ws.send(JSON.stringify("ping"));
f.close = ()=>ws.close();
return f
}
c=new wsConnection('wss://echo.websocket.org');
setTimeout(()=>c("Hello world...orld...orld..orld...d"),5000);
setTimeout(()=>c.close(),10000);
setTimeout(()=>c("I am still alive!"),20000);
<pre>
This code will create a websocket which will
reconnect automatically after 5 seconds from disconnection.
An automatic disconnection is simulated after 10 seconds.
WebSocket 的客户端关闭事件有一个wasClean属性,这对我很有用。在客户端计算机进入睡眠模式等情况或服务器意外停止等情况下,它似乎设置为 true。如果您手动关闭套接字,它设置为 false,在这种情况下您不想打开套接字自动再次。以下来自 Angular 7 项目的代码。我在服务中有这个代码,所以它可以从任何组件中使用。
notifySocketClose(event) {
if (!event.wasClean) {
setTimeout(() => {
this.setupSocket()
}, 1000);
}
}
setupSocket() { // my function to handle opening of socket, event binding etc.
.....
.....
this.websocketConnection = this.websocketConnection ? this.websocketConnection : new WebSocket(socketUrl);
this.websocketConnection.onclose = this.notifySocketClose.bind(this);
}
}
.....
.....
最后,我在vue+ts中让ws自动重连,类似如下:
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);
// }
};
}