PORT=1337 node indexto start the servertelnet localhost 1227to connect to the server
Last active
August 14, 2022 05:25
-
-
Save 8bitDesigner/8854118 to your computer and use it in GitHub Desktop.
Tiny chat server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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