Compare commits

...

2 Commits

3 changed files with 85 additions and 81 deletions

View File

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

View File

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

View File

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