88 lines
1.9 KiB
JavaScript
88 lines
1.9 KiB
JavaScript
// Constants and variables
|
|
// const wsUri = "ws://localhost:32715";
|
|
const wsUri = "wss://chat.glitch-in.space:443/ws/";
|
|
|
|
class Client {
|
|
constructor(wsUri) {
|
|
this.wsUri = wsUri;
|
|
|
|
// Create WebSocket and set callbacks
|
|
console.log("Initialize Client...")
|
|
this.webSocket = new WebSocket(wsUri);
|
|
this.webSocket.onopen = this.onOpen.bind(this);
|
|
this.webSocket.onclose = this.onClose.bind(this);
|
|
this.webSocket.onmessage = this.onMessage.bind(this);
|
|
this.webSocket.onerror = this.onError.bind(this);
|
|
}
|
|
|
|
// WebSocket event handlers
|
|
onOpen(evt) {
|
|
console.log("Connected to " + wsUri);
|
|
|
|
// Send init command containing chat ID and nickname
|
|
this.sendInit();
|
|
}
|
|
|
|
onClose(evt) {
|
|
console.log("Connection closed (code " + evt.code + ").");
|
|
}
|
|
|
|
onMessage(evt) {
|
|
console.log("Received: " + evt.data);
|
|
this.parseMessage(evt.data);
|
|
}
|
|
|
|
onError(evt) {
|
|
console.error("Connection error: ", evt);
|
|
}
|
|
|
|
// Command senders
|
|
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);
|
|
this.webSocket.send(initJson);
|
|
}
|
|
|
|
// Message parsing
|
|
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() {
|
|
let client = new Client(wsUri);
|
|
});
|