0

Add in the optimization where multiple websocket events can exist within a single message

This commit is contained in:
Gabe Kangas 2021-07-26 19:23:15 -07:00
parent 8b2747e4d7
commit fac06257ad
2 changed files with 30 additions and 17 deletions

View File

@ -135,6 +135,14 @@ func (c *ChatClient) writePump() {
log.Debugln(err) log.Debugln(err)
} }
// Optimization: Send multiple events in a single websocket message.
// Add queued chat messages to the current websocket message.
n := len(c.send)
for i := 0; i < n; i++ {
_, _ = w.Write(newline)
_, _ = w.Write(<-c.send)
}
if err := w.Close(); err != nil { if err := w.Close(); err != nil {
return return
} }

View File

@ -153,26 +153,31 @@ export default class Websocket {
pass it along to listeners. pass it along to listeners.
*/ */
onMessage(e) { onMessage(e) {
try { // Optimization where multiple events can be sent within a
var model = JSON.parse(e.data); // single websocket message. So split them if needed.
} catch (e) { var messages = e.data.split('\n');
// console.log(e, e.data); for (var i = 0; i < messages.length; i++) {
return; try {
} var model = JSON.parse(e.data);
} catch (e) {
// console.log(e, e.data);
return;
}
if (!model.type) { if (!model.type) {
console.error('No type provided', model); console.error('No type provided', model);
return; return;
} }
// Send PONGs // Send PONGs
if (model.type === SOCKET_MESSAGE_TYPES.PING) { if (model.type === SOCKET_MESSAGE_TYPES.PING) {
this.sendPong(); this.sendPong();
return; return;
} }
// Notify any of the listeners via the raw socket message callback. // Notify any of the listeners via the raw socket message callback.
this.notifyRawMessageListeners(model); this.notifyRawMessageListeners(model);
}
} }
// Reply to a PING as a keep alive. // Reply to a PING as a keep alive.