fix race condition while connecting

This commit is contained in:
Robin Appelman 2017-04-14 16:03:31 +02:00
commit 2d93c8e9ff
3 changed files with 15 additions and 9 deletions

View file

@ -3,7 +3,7 @@
"description": "Create rcon connections using websockets", "description": "Create rcon connections using websockets",
"author": "Robin Appelman <robin@icewind.nl>", "author": "Robin Appelman <robin@icewind.nl>",
"license": "MIT", "license": "MIT",
"version": "0.2.0", "version": "0.2.1",
"main": "lib/rcon.js", "main": "lib/rcon.js",
"scripts": { "scripts": {
"build": "babel src --out-dir lib" "build": "babel src --out-dir lib"

View file

@ -56,7 +56,8 @@ export default class Connection {
return; return;
} }
this.errorCount++; this.errorCount++;
Promise.delay(2500).then(() => { console.log('failed to connect');
this.delay(2500).then(() => {
if (this.connectPromise) { if (this.connectPromise) {
this.rcon.connect(); this.rcon.connect();
} else { } else {

View file

@ -11,48 +11,53 @@ export default class WebRcon extends EventEmitter {
this.queue = []; this.queue = [];
this.authenticated = false; this.authenticated = false;
this.connected = false; this.connected = false;
this.connecting = false;
} }
connect () { connect () {
if (this.connected) { if (this.connected || this.connecting) {
return; return;
} }
this.connecting = true;
this.socket = new WebSocket('ws://' + this.host + ':' + this.port, 'foo'); this.socket = new WebSocket('ws://' + this.host + ':' + this.port, 'foo');
this.socket.onopen = () => { this.socket.onopen = () => {
if (this.socket.readyState === 1) { if (this.socket.readyState === 1) {
this.socket.send(this.password); this.socket.send(this.password);
this.connected = true;
this.emit('connect'); this.emit('connect');
setTimeout(() => { setTimeout(() => {
for (let message of this.queue) { for (let message of this.queue) {
this.socket.send(message); this.socket.send(message);
} }
this.queue = []; this.queue = [];
this.connecting = false;
this.connected = true;
}, 100); }, 100);
} }
}; };
this.socket.onmessage = (data) => { this.socket.onmessage = ({data}) => {
if (data.data === 'authenticated') { if (data === 'authenticated') {
this.authenticated = true; this.authenticated = true;
} else { } else {
if (!this.authenticated) { if (!this.authenticated) {
this.emit('error', 'not authenticated'); this.emit('error', 'not authenticated');
} }
this.emit('response', data.data) this.emit('response', data)
} }
}; };
this.socket.onerror = (error) => { this.socket.onerror = (error) => {
this.connecting = false;
this.emit('error', error); this.emit('error', error);
}; };
this.socket.onclose = () => { this.socket.onclose = () => {
this.connecting = false;
this.emit('close'); this.emit('close');
}; };
} }
send (string) { send (string) {
this.connect(); if (!this.connected) {
if (this.socket.readyState !== 1) {
this.queue.push(string); this.queue.push(string);
this.connect();
} else { } else {
this.socket.send(string); this.socket.send(string);
} }