lab12: impl

This commit is contained in:
2026-04-07 15:37:21 -07:00
parent 7661769b52
commit 2ef46d20c0

View File

@@ -8,24 +8,56 @@ const NAME_LEN = 10;
var srvr = net.createServer(); var srvr = net.createServer();
var clientList = []; var clientList = [];
srvr.on('connection', function(client) { srvr.on('connection', function (client) {
client.name = calcName(client.remoteAddress, client.remotePort); client.name = calcName(client.remoteAddress, client.remotePort);
client.write('Welcome, ' + client.name + eol); client.write('Welcome, ' + client.name + eol);
clientList.push(client);
// client.on("data", function (data) {
// **YOUR CODE HERE** if (data.at(0) !== "\\".charCodeAt(0)) {
// broadcast(data, client);
// First, add the client to clientList. return;
// }
// Next, add a listener to the client for a 'data' event. command = data
// This event means that the client typed something in. .subarray(1)
// Broadcast that message to all **other** clients in clientList. .toString()
// .split(/[\s\r\n]+/)
// For extra challenges, try adding the following functionality: .filter((s) => s.length > 0);
// 1) Typing '\list' will list the names of all other users. console.log(command);
// 2) Typing '\rename <newname>' will let the user specify a new name for himself/herself. switch (command[0]) {
// 3) Typing '\private <name> <msg>' will send a message only to the specified user. case "list":
const list = clientList.map((c) => c.name).join(eol);
client.write("Connected Users" + eol + list + eol);
break;
case "rename":
if (command.length !== 2) {
client.write("Usage: \\rename <newname>" + eol);
break;
}
const oldName = client.name;
client.name = command[1];
client.write("You are now known as " + client.name + eol);
broadcast(oldName + " is now known as " + client.name + eol, client);
break;
case "private":
if (command.length < 3) {
client.write("Usage: \\private <name> <msg>" + eol);
break;
}
const targetName = command[1];
const msg = command.slice(2).join(" ");
const targetClient = clientList.find((c) => c.name === targetName);
if (targetClient) {
targetClient.write("(Private) " + client.name + " says " + msg + eol);
client.write("(Private) To " + targetClient.name + ": " + msg + eol);
} else {
client.write("User " + targetName + " not found." + eol);
}
break;
default:
client.write("Unknown command: " + command[0] + eol);
}
});
}); });
function calcName(remoteAddress, remotePort) { function calcName(remoteAddress, remotePort) {
@@ -34,6 +66,14 @@ function calcName(remoteAddress, remotePort) {
return h.substring(0, NAME_LEN); return h.substring(0, NAME_LEN);
} }
function broadcast(data, client) {
for (var i in clientList) {
if (client !== clientList[i]) {
clientList[i].write(client.name + " says " + data);
}
}
}
srvr.listen(9000); srvr.listen(9000);