Skip to content

Instantly share code, notes, and snippets.

@willowiscool
Created May 11, 2018 14:42
Show Gist options
  • Save willowiscool/8c3f073a4832cc209388eab79b275866 to your computer and use it in GitHub Desktop.
Save willowiscool/8c3f073a4832cc209388eab79b275866 to your computer and use it in GitHub Desktop.
A chat server with node's net module.

How to use

Run the file. The port is on the last line (no. 13) so you can change that.

In another terminal, on the local network or on the same computer, type nc <local IP of server (or localhost)> <port (default 9000>. Then, you can type stuff to send it, and type /nick <nickname> to set your nickname. You can connect with as many terminals as you want. You can also port-forward that port to be able to access the chat room outside of the local network.

Great!

let net = require("net");
let connections = [];
net.createServer(conn => {
connections.push(conn);
conn.on("data", data => {
if (data.toString().startsWith("/nick ")) conn.nick = data.toString().substring(6).trim();
connections.forEach(el => {
if (el === conn) return;
el.write(`${conn.nick || conn.address().address}: ${data}`);
})
});
conn.on("end", () => connections.splice(connections.indexOf(conn), 1))
}).listen(9000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment