Compare commits

..

No commits in common. "98c89f0702374d7883eb09673d058acb9aa35654" and "fd6a40cb0d3931847df6b7fd5c9ed260dc3122eb" have entirely different histories.

3 changed files with 69 additions and 73 deletions

View File

@ -11,7 +11,6 @@
<h1>InstantChat</h1>
<script src="js/settings.js"></script>
<script src="js/client.js"></script>
</body>

View File

@ -1,41 +1,47 @@
"use strict";
// Constants and variables
// const wsUri = "ws://localhost:32715";
const wsUri = "wss://chat.glitch-in.space:443/ws/";
let websocket;
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);
// 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
onOpen(evt) {
console.log("Connected to " + this.wsUri);
function onOpen(evt) {
console.log("Connected to " + wsUri + ".");
// Send init command containing chat ID and nickname
this.sendInit();
sendInit();
}
onClose(evt) {
function onClose(evt) {
console.log("Connection closed (code " + evt.code + ").");
}
onMessage(evt) {
function onMessage(evt) {
console.log("Received: " + evt.data);
this.parseMessage(evt.data);
parseMessage(evt.data);
}
onError(evt) {
function onError(evt) {
console.error("Connection error: ", evt);
}
// Command senders
sendInit() {
function sendInit() {
// Define command as JSON object
let initObj = {
action: "init",
@ -46,11 +52,11 @@ class Client {
// Send command as JSON string
let initJson = JSON.stringify(initObj);
console.log("Sending init: " + initJson);
this.webSocket.send(initJson);
websocket.send(initJson);
}
// Message parsing
parseMessage(msgString) {
function parseMessage(msgString) {
try {
let msg = JSON.parse(msgString);
@ -77,10 +83,8 @@ class Client {
console.error("Error parsing message JSON: " + e.message);
}
}
}
// Run script after page is loaded
$(function() {
const wsUri = AppSettings.serverWsUri;
let client = new Client(wsUri);
init();
});

View File

@ -1,7 +0,0 @@
"use strict";
// Global settings object
const AppSettings = {
// serverWsUri: "ws://localhost:32715",
serverWsUri: "wss://chat.glitch-in.space:443/ws/",
};