WebSocket:如何在它死后自动重新连接

编程入门 行业动态 更新时间:2024-10-24 18:17:50
本文介绍了WebSocket:如何在它死后自动重新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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) };

当我第一次连接到套接字时,我必须首先向服务器发送一条消息来验证自己和订阅频道。

When I first connect to the socket, I must first send a message to the server to authenticate myself and subscribe to channels.

我遇到的问题是套接字服务器有时不可靠并触发 onerror 和 onclose 'ws'对象的事件。

The problem I have is that sometimes the socket server is unreliable and that triggers the onerror and onclose events of the 'ws' object.

问题:什么是一个好的设计模式,允许我,无论何时套接字关闭或遇到错误,等待10秒然后重新连接到套接字服务器(和将初始消息重新发送到服务器)

Question: What is a good design pattern that would allow me, whenever the socket closes or encounters an error, wait for 10 seconds and then reconnect to the socket server (and resend the initial message to the server)

推荐答案

这是我最终的结果。它适用于我的目的。

Here is what I ended up with. It works for my purposes.

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();

更多推荐

WebSocket:如何在它死后自动重新连接

本文发布于:2023-11-05 04:52:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:死后   如何在   WebSocket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!