Implementation of Multi person Chat Room by js Code

  • 2021-12-05 05:29:21
  • OfStack

This article example for everyone to share the js code to achieve multi-person chat room specific code, for your reference, the specific content is as follows

Design requirements:

1) Users should log in to the chat room by registering
2) The chat room can show all online users
3) Before each chat, display the user name that sent the chat.
4) Can have private chat.
5) When users enter and leave the chat room, the system will broadcast in the chat room

The code for config. js is as follows


module.exports={
    "port":3000,
    "host":"127.0.0.1"
}

The code for broadcast. js is as follows


exports.broadcast=function (data,users) {
    var from=data.from;
    var message=data.message;
    message = from+" Say : "+message;
    // Build message 
    var send={
        mstype:"broadcast",
        message:message
    };
    send =new Buffer(JSON.stringify(send));
    // Traverses all users of the user group and exits all users of the sender 
    for(var username in users){
        if(username!=from){
            users[username].write(send);
        }
    }
};

The code for Signup. js is as follows


exports.signup = function (socket,data,users) {
// Get the user name of the registered user 
    var username=data.username;
    if(!users[username]){  // Does not exist, save the user name and socket
        users[username]=socket;
        var send={
            mstype:"signup",
            code:1000,
            username:username,
            message:" Successful registration "
        };
        socket.write(JSON.stringify (send));
    }else{//cunzai
        var send={
            mstype:"signup",
            code:1001,
            message: " User name is occupied, please re-enter user name "
        }
        socket.write(JSON.stringify(send));
    }
};

The code for p2p. js is as follows


exports.p2p=function (socket,data,users) {
    var from=data.from;
    var to=data.to;
    var message=data.message;
    var receiver=users[to];
    if(!receiver){// Receiver does not exist 
      var send={
          mstype:"p2p",
          code:2001,
          message:" Users "+to+" Nonexistent "
      }
      socket.write(JSON.stringify(send));
    }else{
        // Send information to the receiver if it exists 
        var send={
            mstype:"p2p",
            code:2000,
            from:from,
            message:from+" Say to you "+message
        }
        receiver.write(JSON.stringify(send));
    }
};

Server server-side code


//p2p  Chatroom server 
var net=require("net");
var config=require("./config");
var broadcast=require("./broadcast");
var p2p=require("./p2p");
var signup=require("./signup");
var users={};
var server=net.createServer();
server.on ("connection",function (socket) {
    socket.on("data",function (data) {
        data = JSON.parse(data);
        switch (data.mstype) {
            case "signup":
                signup.signup(socket, data, users);
                break;
            case "broadcast":
                broadcast.broadcast(data, users);
                break;
            case "p2p":
                p2p.p2p(socket, data, users);
                break;
            default:
                break;
        }
    });
    socket.on("error",function () {
        console.log(" A client exited abnormally ");
    });
});
server.listen(config.port,config.host,function () {
    console.log(" Server on port "+config.port+" Start listening ");
});

The Client client code is as follows:


var net=require("net");
var config=require("./config");
var Client=net.createConnection({
    port:config.port,
    host:config.host
});
var username;
Client.on("connect",function () {
    console.log(" Please enter a user name: ");
    process.stdin.on("data",function (data){
        data=data.toString().trim();
        // Determine whether the user already exists 
        if(! username){
            var send={
                mstype:"signup",
                username:data
            };
            Client.write(JSON.stringify(send));
            return;
        }
        var regex=/(.{1,18}):(.+)/;
        var matches=regex=regex.exec(data);
        if(matches){
            // Can match is p2p
            var from=username;// The sender is itself 
            var to=matches[1];// To whom 
            var message=matches[2];
            // Structure JSON Formal information 
            var send={
                mstype: "p2p",
                from:username,
                to:to,
                message:message
            };
            Client.write(JSON.stringify(send));
        }else{
            // Broadcast 
            var send={
                mstype:"broadcast",
                from:username,
                message:data
            };
            Client.write(JSON.stringify(send));
        }
    });
});
Client.on("data",function (data) {
    data=JSON.parse(data);
    switch (data.mstype) {
        case "signup":
            var code=data.code;
            switch (code) {
                case 1000:
                    username=data.username;
                    console.log(data.message);
                    break;
                case 1001:
                    console.log(data.message);
                    break;
                default:
                    break;
            }
            break;
        case "broadcast":
            console.log(data.message);
            break;
        case "p2p":
            var code=data.code;
            switch (code) {
                case 2000:
                    console.log(data.message);
                    break;
                case 2001:
                    console.log(data.message);
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
});
Client.on("error",function () {
    console.log(" The chat room is closed! ! ");
})

Related articles: