js code to realize multi-person chat room

js code to realize multi-person chat room

This article example shares the specific code of js code to implement a multi-person chat room 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 display all online users
3) Before each chat content, the user name that sent the chat content is displayed.
4) Private chat is available.
5) When users enter and leave the chat room, the system will broadcast in the chat room

The config.js code is as follows

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

The broadcast.js code is as follows

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

Signup.js code is as follows

exports.signup = function (socket,data,users) {
//Get the username of the registered user var username=data.username;
    if(!users[username]){ //If it does not exist, save the username and socket
        users[username]=socket;
        var send = {
            mstype:"signup",
            code:1000,
            username:username,
            message: "Registration successful"
        };
        socket.write(JSON.stringify(send));
    }else{//cunzai
        var send = {
            mstype:"signup",
            code:1001,
            message: "The username has been taken, please re-enter the username"
        }
        socket.write(JSON.stringify(send));
    }
};

The p2p.js code 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){//The receiver does not exist var send={
          mstype:"p2p",
          code:2001,
          message: "user"+to+"does not exist"
      }
      socket.write(JSON.stringify(send));
    }else{
        //If it exists, send information to the receiver var send={
            mstype:"p2p",
            code:2000,
            from:from,
            message:from+"to you"+message
        }
        receiver.write(JSON.stringify(send));
    }
};

Server code

//p2p chat room 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 starts listening at port"+config.port+"");
});

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 your username:");
    process.stdin.on("data",function (data){
        data=data.toString().trim();
        // Check if 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){
            //If it matches, it is p2p
            var from=username;//The sender is yourself var to=matches[1];//To whom is it sent var message=matches[2];
            //Construct JSON format 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("Chat room is closed!!");
})

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • A simple chat room function sharing implemented by nodejs
  • Use Angular, Nodejs, and socket.io to build chat rooms and multi-person chat rooms
  • js to write a simple chat room function
  • AngularJS+Node.js to implement online chat room
  • Ajax PHP JavaScript MySQL to achieve a simple non-refresh online chat room
  • JavaScript imitates chat room chat records
  • Implementing a simple chat room with javascript
  • Nodejs realizes multi-room simple chat room function
  • NodeJS implements a chat room function
  • Using sockets to create private and public chat rooms in Node.js

<<:  Use CSS to draw a file upload pattern

>>:  Nginx Layer 4 Load Balancing Configuration Guide

Recommend

Example of how to implement value transfer between WeChat mini program pages

Passing values ​​between mini program pages Good ...

Vant+postcss-pxtorem implements browser adaptation function

Rem layout adaptation The styles in Vant use px a...

4 ways to implement routing transition effects in Vue

Vue router transitions are a quick and easy way t...

Detailed tutorial on installing Python 3.6.6 from scratch on CentOS 7.5

ps: The environment is as the title Install possi...

Win2008 Server Security Check Steps Guide (Daily Maintenance Instructions)

The document has been written for a while, but I ...

A Different Kind of "Cancel" Button

The “Cancel” button is not part of the necessary ...

Tutorial on installing VMWare15.5 under Linux

To install VMWare under Linux, you need to downlo...

The most common declaration merge in TS (interface merge)

Table of contents 1. Merge interface 1.1 Non-func...

How to change the host name in Linux

1. View the current host name [root@fangjian ~]# ...

Issues with upgrading Python and installing Mongodb drivers under Centos

Check the Python version python -V If it is below...

SQL implements LeetCode (180. Continuous numbers)

[LeetCode] 180. Consecutive Numbers Write a SQL q...

11 Reasons Why Bootstrap Is So Popular

Preface Bootstrap, the most popular front-end dev...

mysql 5.7.11 winx64.zip installation and configuration method graphic tutorial

Install and configure the MySql database system. ...

Three ways to configure Nginx virtual hosts (based on domain names)

Nginx supports three ways to configure virtual ho...