Skip to content

Instantly share code, notes, and snippets.

@ppeeou
Created August 7, 2017 06:48
Show Gist options
  • Select an option

  • Save ppeeou/4ad3a3e8eb590f508fc8a6558c1645d4 to your computer and use it in GitHub Desktop.

Select an option

Save ppeeou/4ad3a3e8eb590f508fc8a6558c1645d4 to your computer and use it in GitHub Desktop.
websocket
(function (nameSpace) {
function createMethod(method, options, stateCallback) {
var that = this;
this[method] = function () {
if (stateCallback && stateCallback.apply) {
stateCallback(method);
}
if (options[method] && options[method].apply) {
options[method].apply(that, arguments);
}
};
}
function SocketWrapper(options) {
var ws,
events = ['onopen', 'onmessage', 'onclose', 'onerror'],
i, len, prop = {
opened: false,
closed: false,
error: false
},
method;
if (typeof options === 'undefined' || !options) {
throw 'ArgumentException: please add default constructor options';
}
this.queue = [];
this.onEventTrigger = function (eventName, callback) {
var i, len;
if (eventName === 'onopen') {
prop.opened = true;
prop.closed = false;
// openend send queue
if (this.queue.length > 0) {
for (i = this.queue.length; --i >= 0;) {
this.send.apply(this, this.queue[0]);
this.queue.splice(0, 1);
}
}
}
if (eventName === 'onerror') {
prop.error = true;
}
if (eventName === 'onclose') {
prop.opened = false;
prop.closed = true;
}
};
this.init = function (path, msgOption) {
let protocol = ((location.protocol === 'https:') ? 'wss://' : 'ws://');
let url = protocol + location.hostname +
((location.port) ? (':' + location.port) : '') + '/' + path;
var cb = this.onEventTrigger.bind(this);
console.log('url ', url);
ws = new WebSocket(url);
if (msgOption) {
options['onmessage'] = msgOption;
}
for (i = 0; i < events.length; i++) {
method = events[i];
createMethod.apply(ws, [method, options, cb]);
}
};
this.send = function () {
if (prop.closed) {
throw 'InvalidOperation: Cannot send messages to a closed Websocket!';
}
if (!prop.opened) {
this.queue.push(arguments);
} else {
ws.send.apply(ws, arguments);
}
};
return this;
}
window.SocketWrapper = SocketWrapper;
}(window));
export default new window.SocketWrapper({
onopen: function () {
// let sendmsg = 'connect websocket';
// this.send(sendmsg);
},
onmessage: function (event) {
if (!event.isTrusted) return;
if (event.type == 'message') {
console.log(event.data);
}
},
onclose: function () {
socket = null;
},
onerror: function () {
console.log('error occured, oh no!');
console.error(arguments);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment