commit 8fcdffa89d90e2e90414bf537299818b5fff7ff1
parent a115f551d05bf9b3b126c15b50ed2145825773c6
Author: Matthew Horan <matt@matthoran.com>
Date: Sun, 6 Jan 2019 20:02:23 -0500
Reconnect on connection loss
When WeechatRN goes into the background, at some point the WebSocket
will be closed. Track whether we've successfully connected and then
reconnect when this happens.
Unfortunately the best way to determine this seems to be via an onerror
handler, as a code is not provided for this state in onerror.
Diffstat:
1 file changed, 28 insertions(+), 6 deletions(-)
diff --git a/src/lib/weechat/connection.ts b/src/lib/weechat/connection.ts
@@ -10,6 +10,10 @@ export default class WeechatConnection {
ssl: boolean;
compressed: boolean;
websocket: WebSocket;
+ onSuccess: (conn: WeechatConnection) => any;
+ onError: (event: Event) => any;
+ connected: boolean;
+ reconnect: boolean;
constructor(dispatch) {
this.dispatch = dispatch;
@@ -26,18 +30,24 @@ export default class WeechatConnection {
this.hostname = host;
this.password = password;
this.ssl = ssl;
+ this.onSuccess = onSuccess;
+ this.onError = onError;
+ this.openSocket();
+ }
+
+ openSocket() {
this.websocket = new WebSocket(
`${this.ssl ? "wss" : "ws"}://${this.hostname}/weechat`
);
- this.websocket.onopen = () => this.onopen(onSuccess);
+ this.websocket.onopen = () => this.onopen();
this.websocket.onmessage = event => this.onmessage(event);
- this.websocket.onerror = onError;
- this.websocket.onclose = () => this.close();
+ this.websocket.onerror = event => this.handleError(event);
+ this.websocket.onclose = event => this.close(event);
}
- onopen(callback) {
+ onopen() {
this.dispatch({
type: "SET_CONNECTION_INFO",
hostname: this.hostname,
@@ -50,15 +60,27 @@ export default class WeechatConnection {
}\n`
);
this.send("(version) info version");
- callback(this);
+ this.connected = true;
+ this.onSuccess(this);
+ }
+
+ handleError(event) {
+ this.reconnect = this.connected && true;
+ this.onError(event);
}
- close() {
+ close(event) {
+ this.connected = false;
this.send("quit");
this.websocket.close();
this.dispatch({
type: "DISCONNECT"
});
+
+ if (this.reconnect) {
+ this.reconnect = false;
+ this.openSocket();
+ }
}
onmessage(event) {