preface

Recently because of the impact of COVID – 19, I believe you are working at home at this time, district limit 3 days entrance card of one man, one vote, let we can only squat in the home, but we as a programmer, a computer let us enrich enough after each day, knock on the code to work, tired play computer games, tired of listening to music, one’s fingers itch can also play computer network mahjong, wouldn’t it be fun; As for me, I have been working for nearly 2 years and have never published an article. Recently, I have a task at work, which needs to complete a real-time communication function, not only to be able to chat with people, but also to realize the automatic chat of robots. This is the first day of research, socket. IO implementation of multi-person chat room, article content may be more basic, please big guys stop here.

socket.io

Socket. IoAPI document

Socket. IO encapsulates webSocket and adds many other connection methods and functions. The most useful one is custom events. This article applies only to the sending and receiving functions.

messaging

Send events Send data

Socket.emit (custom sent field, data);Copy the code

Two, listen to the event to obtain data

Socket. on(custom listening field,function(data) {
    console.log(data);
})
Copy the code

The service side Server

Initialize the project

// Initialize the project to generate package.json
npm init -y

// The installation depends on Express +socket.io
npm install express socket.io --save

// Create a folder
index.html+app.js
Copy the code

All of the following is in the app.js file:

Create socket. IO instance

// Import dependencies and create instances
let app = require('express') ();// Introduce the Express module
let http = require('http').Server(app);// Import the HTTP module and start the service
let io = require('socket.io')(http);// Import the socket. IO module

// Listen on the port
const port = 3000;
http.listen(port,()=>{
    console.log(`Http is listening to port ${port}`);
})
Copy the code

Start making connections

io.on('connection'.function(socket){})Copy the code

Send and receive events

When writing about events, we should first consider a few questions:

  • 1. We need to know which users are in the chat room, that is, we need a variable to save the information of the users in the chat room (users={});
  • 2. We need to provide users with a list of onlineUsers (onlineUsers=[]), so that users can send messages to a friend individually;
  • 3. Summarize the first two requirements. Three events (1 login event, 2 message sending event, and 3 logout event) sent by the front desk user need to be monitored, and two events need to be sent to the front desk user (1 provide online user list after successful login, 2 send message to a user after sending message).
// Create a variable
let users = {};// Receive all user objects {name1,name2,name3}
let onlineUsers = [];/ / receive all online users array [{name:, id:}, {name:, id:}] or [name1 name2, name3]

// Create an event
io.on('connection'.function(socket){
// Listen for private message events ==private message
    socket.on('private message', (from,to,msg)=>{
      if(to in users){
        users[to].emit('to'+to,{msg,from,to}); }});// Listen for a new user to enter the chat room event ==new user
    socket.on('new user',name=>{
      // Perform this operation only when the user is not in the user list
      if(! (namein users)){
        users[name] = socket;// Save the user's private socket to the user
        onlineUsers.push(name);// Save the user to the online list
      }
      io.emit('online users',onlineUsers);// Tell the foreground user the list of online users
    });
    // Listening user disconnects ==disconnect
    socket.on('disconnect', () = > {let logoutUserName;
      // Iterate over all users to see if they are in a chat room
      for(let obj in users){
        // If in a chat room, prompt to exit and remove in users
        if(users[obj]==socket){
          logoutUserName = obj;
          deleteusers[obj]; }}// Traverses all online users to check whether the user who exits is online
      for(let i in onlineUsers){
        // Remove the user if the user is online
        if(onlineUsers[i]==logoutUserName){
          onlineUsers.splice(i,1); }}// Tell the front desk the list of online users
      io.emit('online users',onlineUsers);
      // Tell all users that the user has left the chat room
      io.emit('user disconnected',logoutUserName); })})Copy the code

At this point, the server side is done, and now the client side.

All of the following are in the index.html file:

The Client Client

Because just for testing, the client page I do very simple, just to test the function, here is the source code:



      
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <meta content="Width =device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" name="viewport">
    <title>Multiplayer chat room</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
    <style>
      li{
        list-style: none;
        margin-bottom: 10px;
      }
      #message_list li{
        height:40px;
        clear: both;
      }
      li span.name{
        max-width: 300px;
        padding:10px 20px;
        background:#af1;
        border-radius: 5px;
      }
      li i{
        margin:0 10px;
        display: inline-block;
        font-style: normal;
        width:40px;height:40px;
        text-align: center;
        line-height: 40px;
        border-radius: 50%;
        border:1px solid #af1;
      }
      #message_list{
        padding:20px;
        max-width: 600px;
        min-height:300px;
        border:1px solid #ccc;
      }
      .rt{
        float: right;
      }
    </style>
  </head>
  <body>
    <ul id="messages">
      <li>Upcoming push:</li>
    </ul>
    <! -- Login interface -->
    <div id='login_div'>Name:<input id="user_name" type="text"><button type="button" id="login">The login</button>
    </div>
    <! Chat screen after login -->
    <div id="div"  style="display:none">
      <p>Online users:<span id='online'></span></p>
      <p>Chat user:<select id="select"></select><br></p>
      <p>Message content:<input type="text" id="message"><button type="button" id="send">send</button></p>
      <p>Message list:</p>
      <ul id="message_list"></ul>
      <p>Real-time dynamics:</p>
      <ul id='message_status'></ul>
    </div>
    <script>
      const ip = 'localhost';
      const port = 3000;
      $(function(){
        var onlineUsers = [],socket,userName = ' ';
        / / login
        $("#login").on("click".function(){$('#login_div').hide()
          socket = io(`ws://${ip}:${port}`);
          socket.on('connect'.function (data) {              
            userName = $('#user_name').val();
            socket.emit('new user',userName);
            $('#div').show();
            // Accept private chat messages
            socket.on('to'+userName, function (data) {
              let $message_list = $('#message_list');
              $message_list.append(`<li><span><span class='name'>${data.msg}&nbsp; <small>from:${data.from}</small></span></span></li>`);
            });
            // Get the current online people
            socket.on("online users".function(data){
              if(data.length>onlineUsers.length){
                $('#message_status').append(`<li><b>${data.slice(- 1) [0]}</b> Enter a chat room & NBSP;The ${new Date().toLocaleTimeString()}</li>`);
              }
              $('#online').html(data.join(', '));
              onlineUsers = data;
              console.log("Refresh online number:"+onlineUsers.length+'people');
              let $select = $('#select');
              $select.empty();
              for(var j=0; j< onlineUsers.length; j++){
                if(userName! =onlineUsers[j]){var option = $("<option value='"+onlineUsers[j]+"' >"+onlineUsers[j]+"</option>"); $select.append(option); }}});// Exit the chat room
            socket.on('user disconnected'.function(name){$('#message_status').append(`<li><b>${name.slice(- 1) [0]}</b> Exit the chat room & NBSP;The ${new Date().toLocaleTimeString()}</li>`); })}); });// Send a message
        $("#send").click(function(e){     
            var msg  = $('#message').val(),
                to = $('#select').val();
            socket.emit('private message',userName,to,msg);
            let $message_list = $('#message_list');
            $message_list.append(`<li><span class='rt'><span class='name'>${msg}&nbsp; &nbsp; <small>to:${to}</small></span></span></li>`);
            $('#message').val(' ');
        });
      });
    </script>
  </body>
</html>
Copy the code

The page looks like this:

  • 1. Before login:

  • 2. After logging in to Jeenk_zou user:

  • 3. Open a new page and log in to a user Lilian again:

  • 4, send message:

  • 5. Reply message:

The user logout function is not enabled because the login status of the user is not recorded when the user logs in. Therefore, the user automatically logs out when the page is refreshed.

conclusion

This article is just two simple files to implement the chat function, socket. IO has many other powerful features, and will continue to explore and update other uses. I’m jeenk_zou. I’m a first-time blogger.