Javascript WebSocket:如何在它死后自动重新连接
当我第一次连接到套接字时,我必须首先向服务器发送一条消息以验证我自己并订阅频道 我遇到的问题是,有时套接字服务器不可靠,会触发Javascript WebSocket:如何在它死后自动重新连接,javascript,websocket,Javascript,Websocket,当我第一次连接到套接字时,我必须首先向服务器发送一条消息以验证我自己并订阅频道 我遇到的问题是,有时套接字服务器不可靠,会触发'ws'对象的onerror和onclose事件 问:什么是好的设计模式,允许我在套接字关闭或遇到错误时等待10秒钟,然后重新连接到套接字服务器(并将初始消息重新发送到服务器)以下是我的结论。这对我来说很有用 var ws = new WebSocket('ws://localhost:8080'); ws.onopen = function () { ws.send
'ws'
对象的onerror
和onclose
事件
问:什么是好的设计模式,允许我在套接字关闭或遇到错误时等待10秒钟,然后重新连接到套接字服务器(并将初始消息重新发送到服务器)以下是我的结论。这对我来说很有用
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function () {
ws.send(JSON.stringify({
.... some message the I must send when I connect ....
}));
};
ws.onmessage = function (e) {
console.log('Got a message')
console.log(e.data);
};
ws.onclose = function(e) {
console.log('socket closed try again');
}
ws.onerror = function(err) {
console.error(err)
};
这就是我的结局。这对我来说很有用
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function () {
ws.send(JSON.stringify({
.... some message the I must send when I connect ....
}));
};
ws.onmessage = function (e) {
console.log('Got a message')
console.log(e.data);
};
ws.onclose = function(e) {
console.log('socket closed try again');
}
ws.onerror = function(err) {
console.error(err)
};
最新答复:
最后,(如果您不使用java),我发现您最好实现自己的“乒乓”策略。(如果您使用的是java,请看一看乒乓球的“动作类型”,我记得不是很清楚…)
在原生Websocket api之上有一个太有趣的包装器,无法很好地添加它
在原生Websocket api之上的包装太有趣了,无法很好地添加它
这对我使用
setInterval
有效,因为客户端连接可能会丢失
function connect() {
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
// subscribe to some channels
ws.send(JSON.stringify({
//.... some message the I must send when I connect ....
}));
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
};
ws.onclose = function(e) {
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
}
connect();
当套接字打开时,不要忘记调用
clearInterval
。这对我使用setInterval
有效,因为客户端连接可能会丢失
function connect() {
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
// subscribe to some channels
ws.send(JSON.stringify({
//.... some message the I must send when I connect ....
}));
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
};
ws.onclose = function(e) {
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
}
connect();
当套接字打开时,不要忘记调用clearInterval。我发现这个包可以解决Websocket连接的重新连接问题。它有一个可配置选项列表,其中一个选项是确定重新连接延迟增长速度的重新连接延迟增长因子。我发现该软件包可以解决Websocket连接的重新连接问题。它有一个可配置选项列表,其中一个选项是重新连接延迟增长因子,它决定重新连接延迟增长的速度。使用异步等待如果套接字关闭或服务器上发生任何错误,客户端将永远尝试每5秒自动连接一次
ngOnInit(): void {
if (window.location.protocol.includes('https')) {
this.protocol = 'wss';
}
this.listenChanges();
}
listenChanges(): void {
this.socket = new WebSocket(`${this.protocol}://${window.location.host}/v1.0/your/url`);
this.socket.onmessage = (event): void => {
// your subscription stuff
this.store.dispatch(someAction);
};
this.socket.onerror = (): void => {
this.socket.close();
};
this.socket.onopen = (): void => {
clearInterval(this.timerId);
this.socket.onclose = (): void => {
this.timerId = setInterval(() => {
this.listenChanges();
}, 10000);
};
};
}
使用async Wait如果套接字关闭或服务器上发生任何错误,客户端将尝试永远每隔5秒自动连接一次
ngOnInit(): void {
if (window.location.protocol.includes('https')) {
this.protocol = 'wss';
}
this.listenChanges();
}
listenChanges(): void {
this.socket = new WebSocket(`${this.protocol}://${window.location.host}/v1.0/your/url`);
this.socket.onmessage = (event): void => {
// your subscription stuff
this.store.dispatch(someAction);
};
this.socket.onerror = (): void => {
this.socket.close();
};
this.socket.onopen = (): void => {
clearInterval(this.timerId);
this.socket.onclose = (): void => {
this.timerId = setInterval(() => {
this.listenChanges();
}, 10000);
};
};
}
这不是一个明确的react问题,但这里有一个react风格的答案: TLDR:您可以使用
setInterval
定期检查websocket连接状态,并在连接关闭时尝试重新连接
类TestComponent扩展了React.Component{
建造师(道具){
超级(道具);
this.state={};
this.connect=this.connect.bind(this);
}
componentDidMount(){
this.interval=setInterval(this.connect,1000);
}
组件将卸载(){
如果(this.ws)this.ws.close();
if(this.interval)clearInterval(this.interval);
}
连接(){
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
if(this.ws==undefined | |(this.ws&&this.ws.readyState==3)){
this.ws=newwebsocket(`ws://localhost:8080`);
this.ws.onmessage=(e)=>{
log(JSON.parse(e.data));
};
}
}
render(){
回来嘿!;
}
}
这不是一个明确的react问题,但这里有一个react风格的答案:
TLDR:您可以使用setInterval
定期检查websocket连接状态,并在连接关闭时尝试重新连接
类TestComponent扩展了React.Component{
建造师(道具){
超级(道具);
this.state={};
this.connect=this.connect.bind(this);
}
componentDidMount(){
this.interval=setInterval(this.connect,1000);
}
组件将卸载(){
如果(this.ws)this.ws.close();
if(this.interval)clearInterval(this.interval);
}
连接(){
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
if(this.ws==undefined | |(this.ws&&this.ws.readyState==3)){
this.ws=newwebsocket(`ws://localhost:8080`);
this.ws.onmessage=(e)=>{
log(JSON.parse(e.data));
};
}
}
render(){
回来嘿!;
}
}
是否重新连接到以前连接到的同一个websocket?因为我正在使用websocket id发送消息,但如果它有新的websocket id,则很难将消息发送到特定的系统。@AlexanderDunaev,超时主要是作为一种简单的方法添加的,以避免在服务器不可用时进行过于激进的重新连接,即网络中断或本地调试服务器关闭。但总的来说,我认为立即重新连接然后以指数级增长的等待时间重新连接比固定的1秒等待稍微好一些。当连接关闭时,websocket实例会发生什么情况。它是垃圾收集的,还是浏览器建立了一堆未使用的对象?setTimeout(connect,1000)是一种更简洁、资源高效的延迟重新连接的方法。也考虑使用S