Skip to content

Instantly share code, notes, and snippets.

@8bitDesigner
Last active August 14, 2022 05:25
Show Gist options
  • Select an option

  • Save 8bitDesigner/8854118 to your computer and use it in GitHub Desktop.

Select an option

Save 8bitDesigner/8854118 to your computer and use it in GitHub Desktop.
Tiny chat server

Usage

  1. PORT=1337 node index to start the server
  2. telnet localhost 1227 to connect to the server
var net = require('net')
, port = process.env.PORT || 3000
, clients = []
, server = net.createServer(handler)
server.listen(port, function() {
console.log('Listening on port', port)
})
// Send a message to every socket, save for `omitSocket`
function send(message, omitSocket) {
clients.forEach(function(s) {
if (!omitSocket || omitSocket !== s) {
s.write(message)
}
})
}
// Run when a client connects
function handler(socket) {
clients.push(socket)
send("Server > Client connected!\n", socket)
// On input
socket.on('data', function(message) {
send(message, socket)
})
// On disconnect
socket.on('end', function(s) {
send("Server > Client disconnected!\n", socket)
clients.splice(clients.indexOf(socket), 1)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment