SHARE
TWEET

Untitled

a guest Jun 20th, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const net = require('net');
  2.  
  3. let server =  net.createServer();
  4. let clientId = 1;
  5. let sockets = {};
  6.  
  7. server.on("connection", (cs) => {
  8.     // console.log(Object.keys(cs));
  9.     console.log("INFO: Client conected!");
  10.    
  11.     cs.clientId = clientId;
  12.     clientId++;
  13.  
  14.     cs.write(`[${cs.clientId}] Please enter your name: `);
  15.  
  16.     cs.on("data", (buffer) => {    
  17.         msg = buffer.toString();
  18.  
  19.         if (!cs.clientName) {
  20.             console.log(`DEBUG: [${cs.clientId}] Client sent name >>>> ` + msg);
  21.             cs.clientName = buffer.toString().trim();
  22.             sockets[cs.clientId] = cs;
  23.             cs.write(`[${cs.clientId}] Welcome [${cs.clientName}] \r\n`);
  24.         }
  25.         else {
  26.             console.log(`DEBUG: [${cs.clientId}] Client sent message > ` + msg);
  27.             Object.keys(sockets).forEach ( id => {
  28.                 console.log(id, cs.clientId, id !== cs.clientId)  // !!! problem: it displays "2 2 true" !!!
  29.  
  30.                 if (id !== cs.clientId) {
  31.                     d = new Date();
  32.                     sockets[id].write(`[${d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()}] [${cs.clientId}] [${cs.clientName}] ${msg}\r\n`);   
  33.                 }
  34.                
  35.             });
  36.            
  37.             // cs.write(`[${cs.clientId}] ${msg} \r\n`);
  38.         }      
  39.     });
  40.    
  41.     cs.on("error", ()=> {
  42.         console.log("INFO: Client error occured");
  43.         consle.log(err.stack)
  44.         // delete session
  45.     });
  46.  
  47.     cs.on('end', () => {
  48.         console.log("INFO: Client disconnected ")
  49.     });
  50.  
  51.    
  52. });
  53.  
  54. server.listen(8080, () => console.log("INFO: Server started"));
  55.  
  56. process.on("SIGINT", () => {
  57.     console.log("Server stopping...")
  58.     process.exit();
  59. });
  60.  
  61. process.on("exit", () => console.log("Server stopped"));
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top