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",
"author": "Robin Appelman <robin@icewind.nl>",
"license": "MIT",
"version": "0.2.0",
"version": "0.2.1",
"main": "lib/rcon.js",
"scripts": {
"build": "babel src --out-dir lib"

View file

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

View file

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