rcon-node
Version:
A TypeScript RCON client library for modern game servers.
67 lines • 2.4 kB
JavaScript
import { createConnection } from "node:net";
import { BaseClient } from "./base.client";
import { readUntil, sendAndRead } from "../utils/seven-days-to-die.utils";
export class SevenDaysToDieClient extends BaseClient {
constructor() {
super(...arguments);
this.socket = null;
this.authenticated = false;
}
connect() {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
this.end();
reject(new Error("Authentication timed out."));
}, this.options.timeout ?? 5000);
this.socket = createConnection({
host: this.options.host,
port: this.options.port,
}, async () => {
this.emit("connect");
try {
if (!this.socket) {
return reject(new Error("Socket closed."));
}
await readUntil(this.socket, /password[:]?/i);
this.socket.write(`${this.options.password}\n`);
await readUntil(this.socket, /Press 'exit' to end session/i);
this.authenticated = true;
this.emit("authenticated");
clearTimeout(timeout);
resolve();
}
catch (err) {
this.end();
clearTimeout(timeout);
reject(err);
}
});
this.socket.on("error", (err) => this.emit("error", err));
this.socket.on("end", () => {
this.authenticated = false;
this.emit("end");
});
});
}
async send(command) {
if (!this.socket || !this.authenticated) {
throw new Error("Not authenticated.");
}
const data = await sendAndRead(this.socket, command, /\n/);
return data.trim();
}
end() {
if (this.socket) {
this.socket.end();
this.socket = null;
this.authenticated = false;
}
}
async testAuthentication() {
const response = await this.send("version");
if (!response.toLowerCase().includes("version")) {
throw new Error("Authentication failed.");
}
}
}
//# sourceMappingURL=seven-days-to-die.client.js.map