Skip to content

Instantly share code, notes, and snippets.

@petecleary
Created October 17, 2017 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petecleary/f817917a8c098ed7f05a38f1f0b0b0d3 to your computer and use it in GitHub Desktop.
Save petecleary/f817917a8c098ed7f05a38f1f0b0b0d3 to your computer and use it in GitHub Desktop.
Web Socket - a starting point for a simple web socket communication object, sending JSON with a to value to target all or one specified user
var piComms = function (userName, setGlobal, pingInterval) {
'use strict';
var user = userName;
var pingTimerId;
var pingTimerInterval = (pingInterval != undefined) ? pingInterval : 5000;
setGlobal = (setGlobal != undefined && setGlobal == false);
var pub = {
setUserName: function (userName) {
user = userName;
},
send : function (msg, to, data) {
if (to == undefined) to = "all";
if (data == undefined) data = {};
var m = {
from: user,
to: to,
message: msg,
data: data
};
pub.socketSend(JSON.stringify(m));
},
socketSend : function (msg) {
socket.send(msg);
},
onrecieve: function (msg) {
},
onopen : function (msg) {
},
onclose : function (msg) {
},
onerror : function (msg) {
}
};
var protocol = location.protocol === "https:" ? "wss:" : "ws:";
var wsUri = protocol + "//" + window.location.host;
var socket = null;
var openSocket = function () {
if (socket === null || socket.readyState === undefined || socket.readyState > 1) {
if (setGlobal) {
socket = window.socket = new WebSocket(wsUri);
} else {
socket = new WebSocket(wsUri);
}
socket.onopen = function (e) {
console.log("socket opened", e);
pingTimerId = setInterval(function () {
openSocket();
}, pingInterval);
try {
pub.onopen(e);
}
catch (ex) { }
};
socket.onclose = function (e) {
console.log("socket closed", e);
try {
pub.onerror(e);
}
catch (ex) { }
};
socket.onmessage = function (e) {
console.log(e);
//make a message object
var msg = JSON.parse(e.data);
try {
if (msg.to.toLowerCase() == "all" || msg.to == user) pub.onrecieve(msg);
}
catch (ex) { }
};
socket.onerror = function (e) {
console.error(e.data);
try {
pub.onerror(e);
}
catch (ex) { }
};
}
}
openSocket();
return pub;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment