From e99406ea638ea5a493209919e90b2f0ab8209580 Mon Sep 17 00:00:00 2001 From: binaryDiv Date: Fri, 23 Nov 2018 21:47:40 +0100 Subject: [PATCH] Client: parse JSON server messages --- public_html/js/client.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/public_html/js/client.js b/public_html/js/client.js index acf438f..e569b7e 100644 --- a/public_html/js/client.js +++ b/public_html/js/client.js @@ -33,6 +33,7 @@ function onClose(evt) { function onMessage(evt) { console.log('Received: "' + evt.data + '".'); + parseMessage(evt.data); } function onError(evt) { @@ -54,6 +55,34 @@ function sendInit() { websocket.send(initJson); } +// Message parsing +function parseMessage(msgString) { + try { + let msg = JSON.parse(msgString); + + switch (msg.type) { + // Response to 'init' command + case 'init': + // TODO + console.log('Got init response: ', msg); + break; + + // Incoming chat message + case 'message': + // TODO + console.log('Got message event: from "' + msg.from + '", text "' + msg.text + '"'); + break; + + // TODO Topic change, user join/leave, error, ... + + default: + console.error('Unknown message type: "' + msg.type + '"'); + } + } + catch (e) { + console.error('Error parsing message JSON: ' + e.message); + } +} // Run script after page is loaded $(function() {