How does NodeJS chat implement the delivery of messages between peer-to-peer clients?

one of the projects that I am very interested in learning node, recently is to make chat tools.

at first, it established a socket connection between the server and the client, and then sent messages to each other.
now I want to communicate between the two clients. Here comes the problem.

The

clients variable is an array in which socket objects are stored. Once there is a new connection, the new socket object push will be put in.

clipboard.png

clients

clipboard.png


..

clipboard.png

clipboard.png

attach all source code:

server.js:

// Socket
const net = require("net");

// 
var clients = [];

var server = net.createServer((socket) => {

    
    //socketpush
    clients.push(socket);

    console.log(`${socket.remoteAddress},${clients.length}`);
 

    socket.on("data",clientData).on("error",(err)=>{

        clients.splice(clients.indexOf(socket),1);
     
        console.log(`${socket.remoteAddress}  ${clients.length}`);
    
    });



    //
    function broadcast(signal){
          console.log(signal);
          // 
          var username = signal.from;
          var message = signal.message;
          // 
          var send = {
              protocal:signal.protocal,
              from:username,
              message:message
            };

          // 
        clients.forEach(client => {
          client.write(JSON.stringify(send));        
        });

    }

    
    //
    function p2p(signal){
        console.log(signal);
        // 
        var username = signal.from;
        var target = signal.to;
        var message = signal.message;

        // 
        var send = {
            protocal:signal.protocal,
            from:username,
            message:message
          };

        console.log(`${username}${target}${message}`); 


        // 
        //clients[target].write(JSON.stringify(send));

  }

   

    function clientData( chunk)  {

        // chunk:broadcast||!
        //              
        // chunk:{"protocal":"broadcast","from":"","message":""}
        // chunk:{"protocal":"p2p",from:"",to:"",message":""}


        try {
            var signal = JSON.parse(chunk.toString().trim());
            var protocal = signal.protocal;

            switch (protocal) {
                case "broadcast":
                    broadcast(signal);
                    break;
                case "p2p":
                    console.log("p2p");
                    p2p(signal);
                    break;
                case "shake":
                    shake(signal);
                    break;
                default:
                    socket.write("protocal");
                    break;
            }

            // var username = signal.from;
            // var message = signal.message;

        }
        catch (err) {
            socket.write("!");
            throw err;
        }

        // 
        // var username = chunk.username;
        // var message = chunk.messge;
        // broadcast(username.message)
    };

});

var port = 2080;

server.listen(port, (err) => {
    if (err) {
        console.log("");
        return false;
    }
    console.log(`${port}`);
});

client.js:
//
const net = require("net");
const readline = require("readline");


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("What is your name? ", (name) => {

    name = name.trim();
    if (!name) throw new Error("");
    //

    //host:192.xx...
    var socket = net.createConnection({ port: 2080 }, () => {



        //;
        var user = {
            protocol: "signin",
            username: name
        }


        console.log(`Welcome ${socket.remoteAddress} ${name} to 2080 chatroom`);

        //
        socket.on("data", (chunk) => {
            try {
                var signal = JSON.parse(chunk.toString().trim());
                var protocal = signal.protocal;
                switch (protocal) {
                    case "broadcast":
                        console.log(`[broadcast]"${signal.from}":${signal.message}`);
                        rl.prompt();
                        break;
                    case "p2p":
                        console.log(`[p2p]${signal.from}:${signal.message}`);
                        rl.prompt();
                        break;
                    default:
                        server.write("");
                        break;
                }
            }
            catch (err) {
                socket.write("!");
                throw err;
            }

        });





        rl.setPrompt(`${name}> `);

        rl.prompt();

        rl.on("line", (line) => {

            line = line.toString().trim();
            var temp = line.split(":");
            var send;

            if (temp.length === 2) {
                //
                console.log("");

                send = {
                    protocal: "p2p",
                    from: name,
                    to: temp[0],
                    message: temp[1]
                };

            } else {
                //

                // chunk:{"protocal":"broadcast","from":"","message":""}
                send = {
                    protocal: "broadcast",
                    from: name,
                    message: line.toString().trim()
                };

            }

            socket.write(JSON.stringify(send));
            

            rl.prompt();

        }).on("close", () => {
            console.log("Have a great day!");
            process.exit(0);
        });

    });

});



use:
-- node server.js
-- node client.js


there is a lot of code. Whether I understand that the last question is

. The
question translates into how to get this particular object out of the array.

as long as push is marked before, who belongs to this socket , such as clients.push ({username:'one', socket:socket}) , and then from clients.find ({username:'one') when needed.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b30994-2bd24.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b30994-2bd24.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?