Init
This commit is contained in:
commit
508a04cf4c
30 changed files with 1545 additions and 0 deletions
40
client/src/js/socket.js
Normal file
40
client/src/js/socket.js
Normal file
|
@ -0,0 +1,40 @@
|
|||
var EventEmitter = require('events').EventEmitter;
|
||||
var _ = require('lodash');
|
||||
|
||||
var sockets = {};
|
||||
|
||||
function createSocket(path) {
|
||||
if (sockets[path]) {
|
||||
return sockets[path];
|
||||
} else {
|
||||
var ws = new WebSocket('ws://' + window.location.host + path);
|
||||
|
||||
var sock = {
|
||||
send: function(type, data) {
|
||||
ws.send(JSON.stringify({ type: type, request: data }));
|
||||
}
|
||||
};
|
||||
|
||||
_.extend(sock, EventEmitter.prototype);
|
||||
|
||||
sockets[path] = sock;
|
||||
|
||||
ws.onopen = function() {
|
||||
sock.emit('connect');
|
||||
};
|
||||
|
||||
ws.onclose = function() {
|
||||
sock.emit('disconnect');
|
||||
};
|
||||
|
||||
ws.onmessage = function(e) {
|
||||
var msg = JSON.parse(e.data);
|
||||
|
||||
sock.emit(msg.type, msg.response);
|
||||
};
|
||||
|
||||
return sock;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = createSocket;
|
Loading…
Add table
Add a link
Reference in a new issue