Some tips on H5 chat application

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/valada/article/details/100588215

H5 chat application to explain

Project Showcase

Here Insert Picture Description

Here Insert Picture Description

Here Insert Picture DescriptionHere Insert Picture Description

conclusion of issue

Repeat single user to log in

The user name of each input compared with the array ar already recorded in the background, it means that if there is repetition.

// 生成数组  var ar="";  socket.on('array', function (val) {    ar = val;    // console.log(ar);});
           if(ar.indexOf(lo.value)==-1){                        sweetAlert("恭喜您,登录成功!");                        socket.emit('setName', lo.value.trim());                        names1(lo.value.trim());                        login1.style.display="none";                        document.querySelector(".bg").style.display = "none";                        document.querySelector(".cd span").style.display = "none";                        document.querySelector(".title img").style.display = "block";                        document.querySelector(".fix").style.display = "block" ;                        document.querySelector(".title").style.display = "block" ;                        document.querySelector(".tit").innerText=lo.value.trim();                        document.querySelector(".swal-button").onclick = function () {                        document.getElementById("text").focus();                        document.querySelector(".fix").addEventListener('click', function (e) {                           if (e.target.nodeName === "LI"&&e.target.innerText != document.querySelector(".tit").innerText) {                                document.querySelector(".fix").style.display="none";                                document.querySelector(".chat_b").style.display="block";                                document.querySelector(".box").style.display="block";                                document.querySelector(".tit").innerText = e.target.innerText;                                document.querySelector("#text").focus();                                onOff=true;                           }                           else{                            sweetAlert("不能跟自己聊天哦~");                           }                        })                    }                }                else{ sweetAlert("不能重复登录哦!"); return }

Not talking to myself

Click to determine whether the same information

          if (e.target.nodeName === "LI"&&e.target.innerText != document.querySelector(".tit").innerText) {                                document.querySelector(".fix").style.display="none";                                document.querySelector(".chat_b").style.display="block";                                document.querySelector(".box").style.display="block";                                document.querySelector(".tit").innerText = e.target.innerText;                                document.querySelector("#text").focus();                                onOff=true;                           }                           else{                            sweetAlert("不能跟自己聊天哦~");                           }

Do not use ajax, do not use the database, how traditional values, how to save information

Sent to the background can be used socket.emit (), then socket.on () listens.

// 传名    function names(value) {        this.name=value;        socket.emit("reg", name);    }    function names1(value) {        this.name1 = value;        socket.emit("join", name1);        document.title = name1 + "的臻美 Chat"    }// 传密码    function pass(value){         socket.emit("pass", value);    }    socket.on("join", function (user) {        this.na = user;     })    socket.on("reg", function (user) {        this.na1 = user;    })    socket.on("pass", function (val) {        // console.log(val);    })// 监听后台名 var users2 = ""; socket.on('users', function (users) {     users2 = users;    //  console.log(users2); }); // 监听后台密码 var pass2=""  socket.on('pass', function (val) {     pass2 = val;    //  console.log(pass2) });

Front-entered the data stored by means of written documents.

//名字socket.on("reg", function (name) {          usocket[name] = socket;          this.i1=name;          io.emit("reg", name);          var myname =this.i1+"\n";          fs.writeFile('./user.xls', myname, {              'flag': 'a'          }, function (err) {              if (err) {                  throw err;              }              // 写入成功后读取测试              fs.readFile('./user.xls', 'utf-8', function (err,data) {                  if (err) {                      throw err;                  }              });          });    })    // 密码socket.on("pass",function(val){        pass[val]=socket;        this.i2=val;        io.emit("pass", val);        var password=this.i2+"\n";         fs.writeFile('./password.xls', password, {              'flag': 'a'          }, function (err) {              if (err) {                  throw err;              }          });    })

How to achieve private message

To provide each user generating a private socket

// 获取在线function broadcast() {    io.sockets.emit("dataval", hashName);}//提供私有 socketfunction privateSocket(toId) {    return (_.findWhere(io.sockets.sockets, {        id: toId    }));}// 封装删除function removeByValue(arr, val) {    for (var i = 0; i < arr.length; i++) {        if (arr[i] == val) {            arr.splice(i, 1);            break;        }    }}// 连接 socketvar io=ws(server);io.on("connection",function(socket){// 写入成功后读取测试fs.readFile('./user.xls', 'utf-8', function (err, data) {    if(data!=null){    var value = data.split('\n');     io.sockets.emit("users", value);        }});// 写入成功后读取测试fs.readFile('./password.xls', 'utf-8', function (err,data) {    if(data!=null){    var pass1=data.split('\n');    io.sockets.emit("pass", pass1);    }});    broadcast();// 生成名字socket.on('setName', function (data) {    var name = data;    hashName[name] = socket.id;    // console.log(hashName[name]);    broadcast();});// 私聊发送socket.on('sayTo', function (data) {    var toName = data.to;    var toId;    console.log(toName);    if (toId = hashName[toName]) {        privateSocket(toId).emit('message1', data);    }});

When two or more users to log in the user list appears to be empty, real-time update list

To re-use an array, each online user to capture, re-assignment

// 统计在线人数var arrh=[]  socket.on('dataval', function (val) {      vf = val;      console.log(vf);        for (let i = 0; i < vf.length; i++) {            // uu++            arrh.push(vf[i])            console.log(arrh)        }              var rf = [...new Set(arrh)]              console.log(rf)              rf=vf              for (let j = 0; j < rf.length; j++) {                    var li = document.createElement("li");                    li.classList.add("active");                    li.innerText = rf[j]                    console.log(rf[j])                    socket.emit("time", rf[j]);                    document.querySelector(".fix").appendChild(li);              }  });  socket.on('join', function (val) {      document.querySelector(".fix").innerHTML = ''  })  socket.on('disconnect', function (val) {      document.querySelector(".fix").innerHTML = ''  })

Sending a message offline

function sock () {    return io.connect("localhost:3003");}// 心跳机制document.addEventListener('visibilitychange', function () {    if (document.visibilityState == 'hidden') {        //记录页面隐藏时间        sock()        console.log('隐藏了')    }})var socket = sock()

Read more: http://gitbook.cn/gitchat/activity/5d71fe9bf755eb3ccec58272

You can also download CSDN community's quality original content GitChat App, read more GitChat exclusive technical content Oh.

FtooAtPSkEJwnW-9xkCLqSTRpBKX

Guess you like

Origin blog.csdn.net/valada/article/details/100588215