From c3c41a346c81ee22ea7acd833c83ac90e99fa7bc Mon Sep 17 00:00:00 2001 From: binaryDiv Date: Fri, 23 Nov 2018 00:45:42 +0100 Subject: [PATCH 1/2] Client: add sendInit() --- public_html/js/client.js | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/public_html/js/client.js b/public_html/js/client.js index 05f0757..acf438f 100644 --- a/public_html/js/client.js +++ b/public_html/js/client.js @@ -23,13 +23,12 @@ function openWebSocket() { function onOpen(evt) { console.log('Connected to ' + wsUri + '.'); - let text = "Meow"; - console.log('Sending "' + text + '".'); - websocket.send(text); + // Send init command containing chat ID and nickname + sendInit(); } function onClose(evt) { - console.log("Connection closed (code " + evt.code + "): ", evt); + console.log("Connection closed (code " + evt.code + ")."); } function onMessage(evt) { @@ -40,6 +39,21 @@ function onError(evt) { console.error('Connection error: ', evt); } +// Command senders +function sendInit() { + // Define command as JSON object + let initObj = { + action: "init", + chat_id: "42", + nickname: "binaryDiv" + }; + + // Send command as JSON string + let initJson = JSON.stringify(initObj); + console.log('Sending init: ' + initJson); + websocket.send(initJson); +} + // Run script after page is loaded $(function() { From e99406ea638ea5a493209919e90b2f0ab8209580 Mon Sep 17 00:00:00 2001 From: binaryDiv Date: Fri, 23 Nov 2018 21:47:40 +0100 Subject: [PATCH 2/2] 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() {