Location>code7788 >text

[work record: c++web chat server] Solved the problem of chat window | Fixed the bug of "chat window that does not distinguish between friends or group chats" | Fixed the bug of "undefined group chat messages" |

Popularity:276 ℃/2025-04-24 21:44:36

Date: 2025.4.24

Learning content:

  • Solved the problem of chat window
  • Fixed the bug "The chat window that does not distinguish between friends or group chats"
  • Fixed the bug of "group chat message undefined"

Personal summary:

I really hope to learn some knowledge about the front-end in the last few times. In fact, I can feel that I can't write the front-end code, and I don't know much about some things, which leads to not being able to implement these ideas at present. However, I personally think it's really not slow to get started. About implementationFixed the bug "The chat window that does not distinguish between friends or group chats"I wanted to directly use brainless AI at the beginning, but found that the mentally retarded AI could not solve this content. I could only calm down and do it, but found that it was not that difficult.(Of course, it may be that this is not difficult, I am too stupid).

Fixed a bug in the chat window

Actually, this is not troublesome, just let the AI ​​run one for me(It still uses the power of AI.

/* Chat area */
       .chat-pane {
         display: flex;
         flex-direction: column;
         height: 100vh; /* Occupy full screen height */
       }

Fixed the bug "The chat window that does not distinguish between friends or group chats"

I feel a little disgusting. First of all, we must save the client order and chat history of each user just like opening a map.

export const chatSessions = new Map();
export const chatSessionsGruop = new Map();

Just like this, I opened two, the first one was with the user and the second one was with group chat.

Let’s talk about one here, after all, it’s almost exactly the same.

Let's break down the problem first:

We must implement it. When we send a message or receive a message, we need to save the message. Is it the time to send or accept it? It should be when receiving the message. After all, when we send a message, in the program design, we also sent a message to ourselves.

Let's take a look at the changes to the handler:

//Process the received message
   16: (data) => {
     const messagesDiv = ("chat-messages");

     (createMessageElement(data));
     // Automatically scroll to the bottom
      = ;

     //Put the message into the session;
     if (("group_id")) {
       const id = parseInt(data.group_id);
       if (!(id)) {
         (id, []);
         ("set group good", id);
       }
       (id).push(data);
     } else {
       //The message you sent to others should be recorded in the chat of others to_id
       const id =
         parseInt(data.from_id) === parseInt()
           ? parseInt(data.to_id)
           : parseInt(data.from_id);

       if (!(id)) {
         (id, []);
         ("set user good", id, typeof id);
       }
       (id).push(data);
     }
   },

Here I will talk about it one by one. First, the first three items are the same as the previous ones. For a simplicity, the contents of the message creation are written into a function:

export function createMessageElement(data) {
  const messageDiv = ("div");
   = `message ${
    ("from_id")
      ? data.from_id === 
        ? "self"
        : ""
      : data.user_id === 
      ? "self"
      : ""
  }`;
   = `
            <div class="content">${}</div>
            <div class="message-time">
                 ${}
            </div>
        `;
  return messageDiv;
}

Then we need to put the received message into the session. Let's distinguish it here. We only discuss chatting with users: for the current client, if the person sending the message is himself, then we record the message in the chat of the person receiving the message. If we are the person receiving the message, we need to record the message in the chat of the person sending the message.

 	if (!(id)) {
        (id, []);
        ("set user good", id, typeof id);
      }
      (id).push(data);

Here is saying: If there is no id in our container, then we will create a log that I debugged, then get to the key of the id and push.

We don’t need to make too much judgment on group chats, after all, they are all stored in the chat records of group chats.

Now that we have saved the message, the reading of the message should be processed when we click on friends or group chat:

Find the callback function that occurs when we click on friends:

import { FriendListHandler } from "./";
 export const friendListView = new FriendListHandler(
   "chat-list",
   (selectedFriend) => {
     // Here is the logic after selecting friends

      = {
       type: "friend",
       id: parseInt(),
       name: ,
     };

     // Clear the chat area
     const messagesDiv = ("chat-messages");
      = "";
     const sessionid = parseInt();
     // Load historical messages
     if ((sessionid)) {
       ("YES");
       (sessionid).forEach((msg) => {
         (createMessageElement(msg));
          = ;
       });
     } else {
       ("NO", sessionid);
     }

     // Update the chat window title
     (
       ".chat-header"
     ).textContent = `Conversation with ${}`;
   }
 );

There are more middle parts here, namely, clear the chat area and then load our historical messages.

If there is a historical message, output each message.

We can just use the same method to handle group chats.

But we have to deal with a mess, just as we were going to add a CHAT_TO_ONE_ACK at that time, we were lazy at that time, and now we need to re-modify the content of the muduo server and add a CHAT_TO_GROUP_ACK.

So probably add some code:

int user_id = js["user_id"].get<int>();
	// std::string user_name = js["user_name"].get<std::string>();
	int group_id = js["group_id"].get<int>();
	Group group = _group_model.GetGroup(group_id);
	User user = _user_modle.Query(user_id);

	json response;
	response["user_id"] = user_id;
	response["user_name"] = ();
	response["group_id"] = group_id;
	response["group_name"] = ();

//...
		if (it != _conn_mp.end())
				{
					auto to_conn = it->();
					response["uid"] = it->();

					Send(to_conn, ());
					continue;
				}

At the same time, our front-end needs to be changed:

// Process the received messages from friends
   16: (data) => {
     if (
        === "friend" &&
       (data.from_id === || data.from_id === )
     ) {
       const messagesDiv = ("chat-messages");

       (createMessageElement(data));
       // Automatically scroll to the bottom
        = ;
     }

     //Put the message into the session;

     //The message you sent to others should be recorded in other people's to_id chat, otherwise it will be recorded in from_id.
     const id =
       parseInt(data.from_id) === parseInt()
         ? parseInt(data.to_id)
         : parseInt(data.from_id);

     if (!(id)) {
       (id, []);
       ("set user good", id, typeof id);
     }
     (id).push(data);
   },
   // Process the received message from group chat
   19: (data) => {
     if (
        === "group" &&
       (parseInt(data.from_id) === parseInt() ||
         data.group_id === )
     ) {
       const messagesDiv = ("chat-messages");

       (createMessageElement(data));
       // Automatically scroll to the bottom
        = ;
     }

     //Put the message into the session;

     const id = parseInt(data.group_id);
     if (!(id)) {
       (id, []);
       ("set group good", id);
     }
     (id).push(data);
   },

Something added here is to make a judgment

if (
       === "friend" &&
      (data.from_id ===  || data.from_id === )
    )

We will only display this message if the currently accepted message is our current chat window.

The same is true for group chats.

At this point, we have implemented the basic functions of friend chat and group chat.

But I now find that after I implemented it, the message accepted in the group chat was undefined.

Fixed the bug where undefined group chat messages were undefined

OK, let me talk first. When looking for a bug, I suddenly found that if one party's currentChat is null, the message sent by the other party will not be recorded in the chat record.

So we need to add a before push to determine whether it is null

It's probably like this:

if ( != null)
       if (
          === "group" &&
         (parseInt(data.from_id) === parseInt() ||
           data.group_id === )
       ) {
         const messagesDiv = ("chat-messages");

         (createMessageElement(data));
         // Automatically scroll to the bottom
          = ;
       }

Regarding undefined, it turns out that I forgot to install text and time in the response on the server, no wonder undefined.

Then a little change was made to the pop-up of the message:

// Add a new message element creation function
 export function createMessageElement(data) {
   const messageDiv = ("div");
   if (("group_id")) {
      = `message ${
       data.user_id === ? "self" : ""
     }`;
      = `
               <div class="content">${}</div>
               <div class="message-user ${
                 data.user_id === ? "self" : ""
               }">${data.user_name}</div>
               <div class="message-time">
                    ${}
               </div>
           `;
   } else {
      = `message ${
       data.from_id === ? "self" : ""
     }`;
      = `
               <div class="content">${}</div>
               <div class="message-time">
                    ${}
               </div>
           `;
   }

   return messageDiv;
 }

I will discuss group chats separately and friends. After all, the display content of group chats is different from that of friends, so it is a bit troublesome to use the three-mesh operator all the time.

Already become a coder

Added a css by the way:

	 . {
        font-size: 16px;
        color: #00fc2a;
        margin-top: 4px;
      }
      .message-user {
        font-size: 16px;
        color: #ca2e2e;
        margin-top: 4px;
      }

So to this point, the content of group chat and friends sending messages was finally successfully implemented.

postscript

So far, we have completed most of the functions we wrote last night, except for that state refresh, but I think it may not be necessary.

So the decision is done here for the time being. The subsequent todo probably includes these:

  • Add friends
  • Add a group chat
  • Create a group chat
  • Registration function

After completing these four, there is currently no front-end that can do. Our subsequent focus will fall on the back end.