From 4211560f20f424cc328efd069fcb0920a5bfcb74 Mon Sep 17 00:00:00 2001 From: binaryDiv Date: Sat, 27 Oct 2018 05:13:14 +0200 Subject: [PATCH] First WebSocket client code --- public_html/js/client.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/public_html/js/client.js b/public_html/js/client.js index 1914f7c..7887471 100644 --- a/public_html/js/client.js +++ b/public_html/js/client.js @@ -1,8 +1,44 @@ +// Constants and variables +var wsUri = "ws://localhost:8765"; + + // Initialization function init() { console.log("Init..."); + openWebSocket(); } +// Open WebSocket +function openWebSocket() { + websocket = new WebSocket(wsUri); + websocket.onopen = function(evt) { onOpen(evt) }; + websocket.onclose = function(evt) { onClose(evt) }; + websocket.onmessage = function(evt) { onMessage(evt) }; + websocket.onerror = function(evt) { onError(evt) }; +} + +// WebSocket event handlers +function onOpen(evt) { + console.log('Connected to ' + wsUri + '.'); + + text = "Meow"; + console.log('Sending "' + text + '".'); + websocket.send(text); +} + +function onClose(evt) { + console.log("Connection closed."); +} + +function onMessage(evt) { + console.log('Received: "' + evt.data + '".'); +} + +function onError(evt) { + console.error('Error: "' + evt.data + '".'); +} + + // Run script after page is loaded $(function() { init();