当我第一次连接到套接字时,我必须首先向服务器发送一条消息来验证自己和订阅频道。
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:如何在它死后自动重新连接
发布评论