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 clientList = [];
srvr.on('connection', function(client) {
srvr.on('connection', function (client) {
client.name = calcName(client.remoteAddress, client.remotePort);
client.write('Welcome, ' + client.name + eol);
clientList.push(client);
//
// **YOUR CODE HERE**
//
// First, add the client to clientList.
//
// Next, add a listener to the client for a 'data' event.
// This event means that the client typed something in.
// Broadcast that message to all **other** clients in clientList.
//
// For extra challenges, try adding the following functionality:
// 1) Typing '\list' will list the names of all other users.
// 2) Typing '\rename <newname>' will let the user specify a new name for himself/herself.
// 3) Typing '\private <name> <msg>' will send a message only to the specified user.
client.on("data", function (data) {
if (data.at(0) !== "\\".charCodeAt(0)) {
broadcast(data, client);
return;
}
command = data
.subarray(1)
.toString()
.split(/[\s\r\n]+/)
.filter((s) => s.length > 0);
console.log(command);
switch (command[0]) {
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) {
@@ -34,6 +66,14 @@ function calcName(remoteAddress, remotePort) {
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);