instantchat/public_html/js/client.js

62 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-10-27 05:13:14 +02:00
// Constants and variables
//const wsUri = "ws://localhost:32715";
const wsUri = "wss://chat.glitch-in.space:443/ws/";
2018-11-11 16:23:44 +01:00
let websocket;
2018-10-27 05:13:14 +02:00
2018-10-27 05:00:11 +02:00
// Initialization
function init() {
console.log("Init...");
2018-10-27 05:13:14 +02:00
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 + '.');
2018-11-23 00:45:42 +01:00
// Send init command containing chat ID and nickname
sendInit();
2018-10-27 05:00:11 +02:00
}
2018-10-27 05:13:14 +02:00
function onClose(evt) {
2018-11-23 00:45:42 +01:00
console.log("Connection closed (code " + evt.code + ").");
2018-10-27 05:13:14 +02:00
}
function onMessage(evt) {
console.log('Received: "' + evt.data + '".');
}
function onError(evt) {
console.error('Connection error: ', evt);
2018-10-27 05:13:14 +02:00
}
2018-11-23 00:45:42 +01:00
// 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);
}
2018-10-27 05:13:14 +02:00
2018-10-27 05:00:11 +02:00
// Run script after page is loaded
$(function() {
init();
});