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

Detailed explanation of the general steps for SQL statement optimization

Preface This article mainly shares with you the g...

How to use async and await in JS

Table of contents 1. async 2. await: 3. Comprehen...

VUE realizes registration and login effects

This article example shares the specific code of ...

Tutorial on using Multitail command on Linux

MultiTail is a software used to monitor multiple ...

jQuery implements the bouncing ball game

This article shares the specific code of jQuery t...

Common ways to optimize Docker image size

The Docker images we usually build are usually la...

WeChat applet development practical skills: data transmission and storage

Combining the various problems I encountered in m...

A brief discussion on the whole process of Vue's first rendering

Table of contents 1. Vue initialization vue entry...

How to perfectly implement the grid layout with intervals on the page

Typical layout examples As shown in the above pic...

Docker build PHP environment tutorial detailed explanation

Docker installation Use the official installation...

A brief discussion on the magical uses of CSS pseudo-elements and pseudo-classes

CSS plays a very important role in a web page. Wi...

Pure CSS custom multi-line ellipsis problem (from principle to implementation)

How to display text overflow? What are your needs...

Login interface implemented by html+css3

Achieve results First use HTML to build a basic f...