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 is not an internal command error solution

The error "mysql is not an internal command&...

Write a publish-subscribe model with JS

Table of contents 1. Scene introduction 2 Code Op...

How to connect to MySQL visualization tool Navicat

After installing Navicat The following error may ...

How to get the width and height of the image in WeChat applet

origin Recently, I am working on requirement A, i...

Nodejs uses readline to prompt for content input example code

Table of contents Preface 1. bat executes js 2. T...

What you need to know about filters in Vue

Table of contents Preface What is a filter How to...

Java uses Apache.POI to export HSSFWorkbook to Excel

Use HSSFWorkbook in Apache.POI to export to Excel...

Exploring the use of percentage values ​​in the background-position property

How background-position affects the display of ba...

Mini Program Development to Implement Unified Management of Access_Token

Table of contents TOKEN Timer Refresher 2. Intern...

Practical example of Vue virtual list

Table of contents Preface design accomplish summa...

Some tips on deep optimization to improve website access speed

Some tips for deep optimization to improve websit...

js data types and their judgment method examples

js data types Basic data types: number, string, b...

Several situations where div is covered by iframe and their solutions

Similar structures: Copy code The code is as foll...

Summary of common MySQL commands

Set change mysqlroot password Enter the MySQL dat...