mirror of
https://github.com/Team254/cheesy-arena-lite.git
synced 2026-03-09 13:46:44 -04:00
51 lines
1.4 KiB
JavaScript
51 lines
1.4 KiB
JavaScript
// Copyright 2014 Team 254. All Rights Reserved.
|
|
// Author: pat@patfairbank.com (Patrick Fairbank)
|
|
//
|
|
// Shared code for initiating websocket connections back to the server for full-duplex communication.
|
|
|
|
var CheesyWebsocket = function(path, events) {
|
|
var that = this;
|
|
var protocol = "ws://";
|
|
if (window.location.protocol == "https:") {
|
|
protocol = "wss://";
|
|
}
|
|
var url = protocol + window.location.hostname;
|
|
if (window.location.port != "") {
|
|
url += ":" + window.location.port;
|
|
}
|
|
url += path;
|
|
|
|
// Insert a default error-handling event if a custom one doesn't already exist.
|
|
if (!events.hasOwnProperty("error")) {
|
|
events.error = function(event) {
|
|
// Data is just an error string.
|
|
console.log(event.data);
|
|
alert(event.data);
|
|
}
|
|
}
|
|
|
|
// Insert an event to allow the server to force-reload the client for any display.
|
|
events.reload = function(event) {
|
|
location.reload();
|
|
};
|
|
|
|
this.connect = function() {
|
|
this.websocket = $.websocket(url, {
|
|
open: function() {
|
|
console.log("Websocket connected to the server at " + url + ".")
|
|
},
|
|
close: function() {
|
|
console.log("Websocket lost connection to the server. Reconnecting in 3 seconds...");
|
|
setTimeout(that.connect, 3000);
|
|
},
|
|
events: events
|
|
});
|
|
};
|
|
|
|
this.send = function(type, data) {
|
|
this.websocket.send(type, data);
|
|
};
|
|
|
|
this.connect();
|
|
};
|