Nodejs implementation of a simple chat room function sharing

  • 2020-03-30 04:32:32
  • OfStack

Today I will implement a simple chat room, the background with nodejs, client and server side of the credit socket.io, which is a relatively mature websocket framework.

The initial work

1. Install express, which hosts socket.io and static pages, and command NPM install express-save, -save to add packages to the package.json file.
2. To install socket. IO, NPM install socket. IO --save.

Write server-side code

First we host the site via express and attach it to the socket.io instance, because the HTTP protocol is required for the initial socket.io connection


var express = require('express'),
    io = require('socket.io'); var app = express(); app.use(express.static(__dirname)); var server = app.listen(8888);
var ws = io.listen(server);

Add a server connection event, announce to all online users when the client connection is successful, and broadcast to other users when the user sends a message.

ws.on('connection', function(client){
    console.log('033[96msomeone is connect033[39m n');
    client.on('join', function(msg){
        //Check for duplicates
        if(checkNickname(msg)){
            client.emit('nickname', ' Nicknames are duplicated !');
        }else{
            client.nickname = msg;
            ws.sockets.emit('announcement', ' system ', msg + ' Joined the chat room !');
        }
    });
    //Listen to send message
    client.on('send.message', function(msg){
        client.broadcast.emit('send.message',client.nickname,  msg);
    });
    //When disconnected, notify other users
    client.on('disconnect', function(){
        if(client.nickname){
            client.broadcast.emit('send.message',' system ',  client.nickname + ' Leave the chat room !');
        }
    }) })

Because the client is identified by a nickname, the server needs a function to detect duplicate nicknames


//Check if the nickname is repeated
var checkNickname = function(name){
    for(var k in ws.sockets.sockets){
        if(ws.sockets.sockets.hasOwnProperty(k)){
            if(ws.sockets.sockets[k] && ws.sockets.sockets[k].nickname == name){
                return true;
            }
        }
    }
    return false;
}

Write customer service side code

Because the server adopts the third party websokcet framework, the front-end page needs to separately refer to the socket.io client code, the source file can be found from the socket.io module, the Windows path is node_modules socket.io\node_modules socket.io-client\dist, there are development version and compressed version, the default reference development version on the line.

The front end mainly handles input nickname checking and message processing. The complete code is as follows:


<!DOCTYPE html>
<html>
<head>
    <title>socket.io Chat room example </title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/reset.css"/>
    <link rel="stylesheet" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/app.css"/>
</head>
<body>
    <div class="wrapper">
         <div class="content" id="chat">
             <ul id="chat_conatiner">
             </ul>
         </div>
         <div class="action">
             <textarea ></textarea>
             <button class="btn btn-success" id="clear"> Clear the screen </button>
             <button class="btn btn-success" id="send"> send </button>
         </div>
    </div>
    <script type="text/javascript" src="js/socket.io.js"></script>
    <script type="text/javascript">           var ws = io.connect('http://172.16.2.184:8888');
          var sendMsg = function(msg){
              ws.emit('send.message', msg);
          }
          var addMessage = function(from, msg){
              var li = document.createElement('li');
              li.innerHTML = '<span>' + from + '</span>' + ' : ' + msg;
              document.querySelector('#chat_conatiner').appendChild(li);               //Set the scroll bar in the content area to the bottom
              document.querySelector('#chat').scrollTop = document.querySelector('#chat').scrollHeight;               //And set the focus
              document.querySelector('textarea').focus();           }           var send = function(){
              var ele_msg = document.querySelector('textarea');
              var msg = ele_msg.value.replace('rn', '').trim();
              console.log(msg);
              if(!msg) return;
              sendMsg(msg);
              //Add a message to your own content area
              addMessage(' you ', msg);
              ele_msg.value = '';
          }           ws.on('connect', function(){
              var nickname = window.prompt(' Enter your nickname !');
              while(!nickname){
                  nickname = window.prompt(' The nickname cannot be null, please enter again !')
              }
              ws.emit('join', nickname);
          });           //Nicknames have duplicate
          ws.on('nickname', function(){
              var nickname = window.prompt(' There is a duplicate nickname. Please enter again !');
              while(!nickname){
                  nickname = window.prompt(' The nickname cannot be null, please enter again !')
              }
              ws.emit('join', nickname);
          });           ws.on('send.message', function(from, msg){
              addMessage(from, msg);
          });           ws.on('announcement', function(from, msg){
              addMessage(from, msg);
          });           document.querySelector('textarea').addEventListener('keypress', function(event){
              if(event.which == 13){
                  send();
              }
          });
          document.querySelector('textarea').addEventListener('keydown', function(event){
              if(event.which == 13){
                  send();
              }
          });
          document.querySelector('#send').addEventListener('click', function(){
              send();
          });           document.querySelector('#clear').addEventListener('click', function(){
              document.querySelector('#chat_conatiner').innerHTML = '';
          });
    </script>
</body>
</html>

Provided here (link: http://xiazai.jb51.net/201410/tools/node-js-chat.rar)

conclusion

Nodejs is a good thing, especially when it comes to handling message communication, network programming, and inherently asynchronous IO.


Related articles: