instantchat/public_html/js/client.js

108 lines
2.4 KiB
JavaScript

"use strict";
class Client {
constructor(wsUri) {
this.wsUri = wsUri;
// Create WebSocket and set internal callbacks
console.log("Initialize Client...")
this.webSocket = new WebSocket(wsUri);
this.webSocket.onopen = this._onSocketOpen.bind(this);
this.webSocket.onclose = this._onSocketClose.bind(this);
this.webSocket.onerror = this._onSocketError.bind(this);
this.webSocket.onmessage = this._onSocketMessage.bind(this);
}
// Internal WebSocket event handlers
_onSocketOpen(evt) {
console.log("Connected to " + this.wsUri);
// Send init command containing chat ID and nickname
this.sendInit();
}
_onSocketClose(evt) {
console.log("Connection closed (code " + evt.code + ").");
}
_onSocketError(evt) {
console.error("Connection error: ", evt);
}
_onSocketMessage(evt) {
console.log("Received: " + evt.data);
this._parseMessage(evt.data);
}
/**
* Sends an arbitrary command as JSON.
*
* commandObj: The command as an object ('action' specifies type of command).
*/
sendCommand(commandObj) {
const commandJson = JSON.stringify(commandObj);
console.log("Sending command: " + commandJson);
this.webSocket.send(commandJson);
}
/**
* Sends the 'init' command which sets up the session. Also sets the chat ID and nickname.
*/
sendInit() {
this.sendCommand({
action: "init",
chat_id: "42",
nickname: "binaryDiv",
});
}
/**
* Sends the 'message' command which sends a chat message to the chat.
*
* msgText: The text of the chat message.
*/
sendChatMessage(msgText) {
this.sendCommand({
action: "message",
text: msgText,
});
}
/**
* Parses an incoming JSON message and dispatches specific events.
*/
_parseMessage(msgString) {
try {
const 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() {
const wsUri = AppSettings.serverWsUri;
let client = new Client(wsUri);
});