diff options
-rw-r--r-- | socket.js | 30 |
1 files changed, 18 insertions, 12 deletions
@@ -4,41 +4,45 @@ const EventEmitter = require('events'); class retryws extends EventEmitter{ // a wrapper on ws that retries on failure constructor(addr) { + super(); let sock; - this.sockdown = true; + let sockdown = true; this.send = (message) => { + console.log(message); if (sockdown){ throw "Socket is down!"; } sock.send(message); } + let self = this; function sockinit(){ // addr is not expected to change, so not handed as input; similarly, sock is not passed in a chain because behavior is expected to be serial (either initializing or retrying) sock = new ws(addr); - sock.on('open', () => { this.emit('open'); sockdown = false; }); - sock.on('close', (err) => { setTimeout(sockinit,1000); sockdown = true; this.emit('close'); }); - sock.on('error', (err) => { sock.close(); }); - sock.on('message', (message) => { this.emit('message',message); }); + sock.on('open', () => { sockdown = false; self.emit('open'); }); + sock.on('close', (err) => { console.log(err); setTimeout(sockinit,1000); sockdown = true; self.emit('close'); }); + sock.on('error', (err) => { console.log(err); sock.close(); }); + sock.on('message', (message) => { self.emit('message',message);}); } + sockinit(); } } class Socket extends retryws { constructor(world='') { // Takes the name of the world, which can be an empty string. - let loc = (name = '') ? '' : `/${name}`; - let addr = `wss://www.yourworldoftext.com/${loc}ws`; + let loc = (world == '') ? '' : `/${world}`; + let addr = `wss://www.yourworldoftext.com/${loc}ws/`; super(addr); this.on('message', (msg)=>{ msg = JSON.parse(msg); - switch (message.kind){ + switch (msg.kind){ case 'write': - this.emit('write', message.accepted, message.rejected); break; // A confirmation message for writes (accepted/rejected updates) + this.emit('write', msg.accepted, msg.rejected); break; // A confirmation message for writes (accepted/rejected updates) case 'cursor': - this.emit('cursor', message.positions, message.sender); break; // Must be used for self-identification + this.emit('cursor', msg.positions, msg.sender); break; // Must be used for self-identification case 'tileUpdate': - this.emit('tileUpdate', message.sender, message.source, message.tiles); break; // Any change by another user or possibly oneself + this.emit('tileUpdate', msg.sender, msg.source, msg.tiles); break; // Any change by another user or possibly oneself case 'fetch': - this.emit('fetch', message.tiles); break; // The response to a fetch request + this.emit('fetch', msg.tiles); break; // The response to a fetch request } }); @@ -55,6 +59,7 @@ class Socket extends retryws { throw "Too many characters to write"; } for (var i=0; i<chars.length; i++){ + chars[i] = chars[i].flat(); chars[i].splice(4,0,0); // chars[i].push(i); } @@ -68,4 +73,5 @@ class Socket extends retryws { } } +exports.retryws = retryws; exports.Socket = Socket; |