Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const net = require('net');
- let server = net.createServer();
- let clientId = 1;
- let sockets = {};
- server.on("connection", (cs) => {
- // console.log(Object.keys(cs));
- console.log("INFO: Client conected!");
- cs.clientId = clientId;
- clientId++;
- cs.write(`[${cs.clientId}] Please enter your name: `);
- cs.on("data", (buffer) => {
- msg = buffer.toString();
- if (!cs.clientName) {
- console.log(`DEBUG: [${cs.clientId}] Client sent name >>>> ` + msg);
- cs.clientName = buffer.toString().trim();
- sockets[cs.clientId] = cs;
- cs.write(`[${cs.clientId}] Welcome [${cs.clientName}] \r\n`);
- }
- else {
- console.log(`DEBUG: [${cs.clientId}] Client sent message > ` + msg);
- Object.keys(sockets).forEach ( id => {
- console.log(id, cs.clientId, id !== cs.clientId) // !!! problem: it displays "2 2 true" !!!
- if (id !== cs.clientId) {
- d = new Date();
- sockets[id].write(`[${d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()}] [${cs.clientId}] [${cs.clientName}] ${msg}\r\n`);
- }
- });
- // cs.write(`[${cs.clientId}] ${msg} \r\n`);
- }
- });
- cs.on("error", ()=> {
- console.log("INFO: Client error occured");
- consle.log(err.stack)
- // delete session
- });
- cs.on('end', () => {
- console.log("INFO: Client disconnected ")
- });
- });
- server.listen(8080, () => console.log("INFO: Server started"));
- process.on("SIGINT", () => {
- console.log("Server stopping...")
- process.exit();
- });
- process.on("exit", () => console.log("Server stopped"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement