-
-
Save handrei/5557bc7555ce5e370364a9884afc03d8 to your computer and use it in GitHub Desktop.
A simple TCP based chat server written in node.js
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
| 'use strict'; | |
| const net=require('net'); | |
| const clients = []; | |
| const server = net.createServer((socket) => { | |
| console.log('client connected'); | |
| socket.name = uuid(); | |
| clients.push(socket); | |
| socket.write('hello '+socket.name +'\n'); | |
| // socket.pipe(socket); | |
| broadcast(socket.name + ' joined the chat\n', socket); | |
| socket.on('data', (data)=>{ | |
| broadcast(socket.name +' > '+data, socket); | |
| }); | |
| socket.on('end', ()=> { | |
| clients.splice(clients.indexOf(socket),1); | |
| broadcast(socket.name+' left the chat\n'); | |
| }); | |
| }); | |
| server.on('error', (err)=>{ | |
| throw err; | |
| }); | |
| server.listen(8124,'localhost', ()=>{ | |
| let adress=server.address(); | |
| console.log('server started on ', adress); | |
| }); | |
| function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)}; | |
| function broadcast(message, sender){ | |
| clients.forEach((client)=>{ | |
| if (client === sender) return; | |
| client.write(message); | |
| }); | |
| process.stdout.write(message); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment