almatyd/index.ts

78 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-12-16 20:57:37 +00:00
if (process.argv[2] == null) {
console.log("No IP specified");
process.exit(1)
}
if (process.argv[3] == null) {
console.log("No port specified");
process.exit(1)
}
const ip = process.argv[2];
const port = Number(process.argv[3]);
class Message {
readonly msg: string;
readonly time: Date;
readonly address: string;
constructor(msg: string, time: Date, address: string) {
this.msg = msg;
this.time = time;
this.address = address;
}
toString() {
let d = this.time
return "[" + d.getDate() + "." + (d.getMonth() + 1) + "." + d.getFullYear() +
2024-12-16 21:28:08 +00:00
" " + d.getHours() + ":" + d.getMinutes() +
2024-12-16 20:57:37 +00:00
"] {" + this.address + "} "
2024-12-16 21:28:08 +00:00
+ this.msg.replace("/\n/g", "$");
2024-12-16 20:57:37 +00:00
}
}
let messages: Message[] = [];
//const net = require('net');
import * as net from "net";
let srv = net.createServer(function(socket: net.Socket) {
let addr = socket.address() as net.AddressInfo;
if (!addr.hasOwnProperty('address')) {
console.log("?!?!?!");
socket.end();
return;
}
socket.on('data', function(data: Buffer | string) {
switch (data[0]) {
case 0x30:
let msg = new Message(String(data.slice(1)), new Date, addr.address);
messages[messages.length] = msg;
console.log("Got message: " + msg.toString());
socket.end()
return;
case 0x31:
2024-12-16 21:01:33 +00:00
let msize = 1
2024-12-16 20:57:37 +00:00
for (const i of messages) {
2024-12-16 21:01:33 +00:00
msize += i.toString().length;
2024-12-16 20:57:37 +00:00
}
socket.write(String(msize));
socket.end();
console.log(addr.address + ", got size request. " + msize);
return;
case 0x32:
console.log(addr.address + ", got messages request.");
let str = "";
for (const i of messages) {
2024-12-16 21:01:33 +00:00
str += i.toString();
2024-12-16 20:57:37 +00:00
}
2024-12-16 21:01:33 +00:00
str += "\n"
2024-12-16 20:57:37 +00:00
console.log("Sending " + str.length + " to " + addr.address);
socket.write(str);
return;
}
console.log(addr.address + "???" + data[0]);
});
socket.on('error', function(e: Error) {
console.log(e.stack);
});
})
console.log("Starting.");
srv.listen(port, ip);