// Constants and variables //const wsUri = "ws://localhost:32715"; const wsUri = "wss://chat.glitch-in.space:443/ws/"; let websocket; // 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 + '.'); // Send init command containing chat ID and nickname sendInit(); } function onClose(evt) { console.log("Connection closed (code " + evt.code + ")."); } function onMessage(evt) { console.log('Received: "' + evt.data + '".'); } 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() { init(); });