Add message queue to socket

This commit is contained in:
Drew DeVault 2017-09-08 16:35:12 +09:00
parent 4d511bba6d
commit 3d8e4f5903
2 changed files with 19 additions and 4 deletions

View File

@ -4,6 +4,8 @@ import { subscribe } from './actions/subscribe';
let ws; let ws;
let serial = 0; let serial = 0;
let transactions = {}; let transactions = {};
let connected = false;
let queue = [];
export default function ws_send(type, body, callback = null) { export default function ws_send(type, body, callback = null) {
const _serial = serial++; const _serial = serial++;
@ -17,7 +19,11 @@ export default function ws_send(type, body, callback = null) {
}; };
const msg = JSON.stringify(obj); const msg = JSON.stringify(obj);
console.log("->", type, obj); console.log("->", type, obj);
if (!connected) {
queue.push(msg);
} else {
ws.send(msg); ws.send(msg);
}
return _serial; return _serial;
} }
@ -37,9 +43,18 @@ function ws_recv(e) {
export function ws_init(uri, open, close) { export function ws_init(uri, open, close) {
ws = new WebSocket(uri); ws = new WebSocket(uri);
ws.addEventListener("open", open); ws.addEventListener("open", () => {
connected = true;
open.apply(this, arguments);
while (queue.length > 0) {
ws.send(queue.pop());
}
});
ws.addEventListener("message", ws_recv); ws.addEventListener("message", ws_recv);
ws.addEventListener("close", close); ws.addEventListener("close", () => {
connected = false;
close.apply(this, arguments);
});
} }
export function ws_disconnect() { export function ws_disconnect() {

View File

@ -36,7 +36,7 @@ function CollapseToggle({ text, onToggle, open }) {
> >
{text} {text}
<FontAwesome <FontAwesome
name={`chevron-${open ? "up" : "down"}`} name={`caret-${open ? "up" : "down"}`}
style={{marginLeft: "0.25rem"}} style={{marginLeft: "0.25rem"}}
/> />
</button> </button>