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

MySQL 5.7.17 Compressed Version Installation Notes

This article shares the installation steps of MyS...

About debugging CSS cross-browser style bugs

The first thing to do is to pick a good browser. ...

Zabbix monitors mysql instance method

1. Monitoring planning Before creating a monitori...

CSS and JS to achieve romantic meteor shower animation

1. Rendering 2. Source code HTML < body > &...

How to create a virtual environment using virtualenv under Windows (two ways)

Operating system: windowns10_x64 Python version: ...

A brief discussion on CSS cascading mechanism

Why does CSS have a cascading mechanism? Because ...

The whole process of IDEA integrating docker to deploy springboot project

Table of contents 1. IDEA downloads the docker pl...

Thumbnail hover effect implemented with CSS3

Achieve resultsImplementation Code html <heade...

Tutorial on installing mysql5.7.17 via yum on redhat7

The RHEL/CentOS series of Linux operating systems...

Use of environment variables in Docker and solutions to common problems

Preface Docker can configure environment variable...

HTML table tag tutorial (13): internal border style attributes RULES

RULES can be used to control the style of the int...

Implementing timed page refresh or redirect based on meta

Use meta to implement timed refresh or jump of th...