1 | dojo.provide("dojox.socket.Reconnect"); |
---|
2 | |
---|
3 | dojox.socket.Reconnect = function(socket, options){ |
---|
4 | // summary: |
---|
5 | // Provides auto-reconnection to a websocket after it has been closed |
---|
6 | // socket: |
---|
7 | // Socket to add reconnection support to. |
---|
8 | // returns: |
---|
9 | // An object that implements the WebSocket API |
---|
10 | // example: |
---|
11 | // You can use the Reconnect module: |
---|
12 | // | dojo.require("dojox.socket"); |
---|
13 | // | dojo.require("dojox.socket.Reconnect"); |
---|
14 | // | var socket = dojox.socket({url:"/comet"}); |
---|
15 | // | // add auto-reconnect support |
---|
16 | // | socket = dojox.socket.Reconnect(socket); |
---|
17 | options = options || {}; |
---|
18 | var reconnectTime = options.reconnectTime || 10000; |
---|
19 | |
---|
20 | var connectHandle = dojo.connect(socket, "onclose", function(event){ |
---|
21 | clearTimeout(checkForOpen); |
---|
22 | if(!event.wasClean){ |
---|
23 | socket.disconnected(function(){ |
---|
24 | dojox.socket.replace(socket, newSocket = socket.reconnect()); |
---|
25 | }); |
---|
26 | } |
---|
27 | }); |
---|
28 | var checkForOpen, newSocket; |
---|
29 | if(!socket.disconnected){ |
---|
30 | // add a default impl if it doesn't exist |
---|
31 | socket.disconnected = function(reconnect){ |
---|
32 | setTimeout(function(){ |
---|
33 | reconnect(); |
---|
34 | checkForOpen = setTimeout(function(){ |
---|
35 | //reset the backoff |
---|
36 | if(newSocket.readyState < 2){ |
---|
37 | reconnectTime = options.reconnectTime || 10000; |
---|
38 | } |
---|
39 | }, 10000); |
---|
40 | }, reconnectTime); |
---|
41 | // backoff each time |
---|
42 | reconnectTime *= options.backoffRate || 2; |
---|
43 | }; |
---|
44 | } |
---|
45 | if(!socket.reconnect){ |
---|
46 | // add a default impl if it doesn't exist |
---|
47 | socket.reconnect = function(){ |
---|
48 | return socket.args ? |
---|
49 | dojox.socket.LongPoll(socket.args) : |
---|
50 | dojox.socket.WebSocket({url: socket.URL || socket.url}); // different cases for different impls |
---|
51 | }; |
---|
52 | } |
---|
53 | return socket; |
---|
54 | }; |
---|