Websocket live room chat tutorial – quick realization of chat room with goeasy

Time:2021-5-6

It’s really indescribable that the fire has been broadcast live in the last two years! Friends often ask, I want to achieve a live chat room or I want to develop a chat room, how to start?
Websocket live room chat tutorial - quick realization of chat room with goeasy

Today, Xiaobian will teach you how to make a chat room with goeasy. Of course, it can also be used for the interaction in the live room. Full set of source code has been open source, GIT address:gitee.com/goeasy-io/GoEasyDemo-htm…
The main purpose of this tutorial is to introduce the implementation ideas for you. In order to ensure that this tutorial can help friends who use different front-end technologies, HTML + jQuery is adopted. In the future, uniapp (Vue / nvue) and small program versions will be launched. You can continue to pay attention to it.

The chat room we are going to implement this time has two interfaces, namely:

  • Login interface
  • Chat room interface

    Sign in

    Websocket live room chat tutorial - quick realization of chat room with goeasy

For the login interface, we expect:

  • Users can enter their own nicknames
  • Users can choose their favorite avatar
  • Users can choose to enter different chat rooms (live rooms)

Implementation steps

Login interface implementation, needless to say, because it is really so easy! A simple interface only contains three simple logics:

  • Verify that you enter a nickname
  • Verify that a avatar is selected
  • Enter the corresponding chat room according to the selection

The next part focuses on the realization of chat room.

Chat room (Live Room)

Websocket live room chat tutorial - quick realization of chat room with goeasy

When we enter a chat room, we expect:

  • Users can see how many users are online, and this number can be updated in real time
  • Users can see the avatars of current online users and update them in real time
  • If a user enters or leaves the chat room
    a. Chat room will have “XXX in” or “XXX left” prompt
    b. The number of online users and their avatar list will be updated automatically
  • Users can speak in chat
  • Users can send props: rockets or Bixin

Implementation steps

Step 1: chat room interface display

1. Initialization:

When the user selects a chat room and displays the chat room interface, we first need to initialize the following work:

  • Initialize the current user, current user, user ID, nickname and avatar
  • Initialize current room ID: currentroomid
  • When initializing the goeasy object, note that the userid parameter must be added (it can be the unique ID of the user, such as UUID or ID. only when the client with the userid set is online or offline, the online or offline reminder will be triggered). At the same time, we need to put the avatar and nickname into UserData. When we receive a user online reminder, we need to know the user’s Avatar and nickname.
  • Initialize onlineusers, which is used to store the number of online users and the list of online users in the current chat room. Take the current room ID (currentroomid) as the channel, execute goeasy.herenow to query the number of online users and user list of the current room, and assign the value to onlineusers. In addition to initializing onlineusers when entering the chat room, when a user enters or leaves, it will also dynamically update onlineusers.
  • Take the ID (currentroomid) of the current chat room as the channel, execute the subscriber method to listen and receive new chat room messages.
  • With the ID of the current room (currentroomid) as the channel, the subscriber presence is executed to monitor the user’s entry and exit events.

Reference code: service.js

//Initialize chat room
this.joinRoom = function(userId,nickName, avatar, roomID) {
        //Initialize current user
        this.currentUser = new User(userId, nickName, avatar);
        //Initialize the current chat room ID
        this.currentRoomId = roomID;
        //Initialize go easy and establish a long connection
        this.goeasy = new GoEasy({
            host: "hangzhou.goeasy.io",
            Appkey: "your appkey,",
            userId: this.currentUser.id,
            userData: '{"nickname":"' + this.currentUser.nickname + '","avatar":"' + this.currentUser.avatar + '"}',
            onConnected: function () {
                console.log( "GoEasy connect successfully.")
            },
            onDisconnected: function () {
                console.log("GoEasy disconnected.")
            }
        });
        //Query the current online user list and initialize the onlineusers object
        this.initialOnlineUsers();
        //Monitor users' online and offline reminders and update the onlineusers object in real time
        this.subscriberPresence();
        //Monitor and receive new messages
        this.subscriberNewMessage();
};

2. Page display:

After initialization, jump to the live room interface and display the following data on the page:

  • The name of the current chat room
  • Chat record, and display the chat room interface
  • Show chat room interface

Reference code: controller.js

//Page switch to chat room interface
function showChatRoom() {
    //Update room name
    $("#chatRoom-header").find(".current-chatRoom-name").text(loginCommand.roomName);

    //Load chat history
    var chatHistory = service.loadChatHistory();
    chatHistory.forEach(function (item) {
        //Show messages sent
        var otherPerson = createCurrentChatRoomPerson(item.senderNickname + ":", item.content)
        $(".chatRoom-content-box").append($(otherPerson));
    });

    //Hide login interface
    $(".chat-login-box").hide();
    //// display chat interface
    $(".chatRoom-box").show();
    //// slide to the last line
    scrollBottom();
}

So far, we have finished the initialization of long connection of goeasy and a static display of chat room. Next, let’s see how to make this chat room move.

Step 2: chat room interaction

1. Update the number of online users and avatar list in real time

The onlineusers object has been initialized in the service. Initialonlineusers method before, but there are users in and out of the chat room at any time, so we need to be able to update the onlineusers in real time when there are users online or offline, and display them on the page in real time.
When we receive a user online reminder, we store the information of new online users in the online user object, onlineusers. When a user leaves, we delete it from the local online user list.

Reference code: service.js

//Monitor the user's up and down time and maintain the onlineusers object
this.subscriberPresence = function() {
    var self = this;
    this.goeasy.subscribePresence({
        channel: this.currentRoomId,
        onPresence: function(presenceEvents) {
            presenceEvents.events.forEach(function(event) {
                var userId = event.userId;
                var count = presenceEvents.clientAmount;
                //Update number of online users
                self.onlineUsers.count = count;
                //If a user enters the chat room
                if (event.action == "join" || event.action == "online") {
                    var userData = JSON.parse(event.userData);
                    var nickName = userData.nickname;
                    var avatar = userData.avatar;
                    var user = new User(userId, nickName, avatar);
                    //Add new users to the online users list
                    self.onlineUsers.users.push(user);
                    //Trigger interface update
                    self.onJoinRoom(user.nickname, user.avatar);
                } else {
                    for (var i = 0; i < self.onlineUsers.users.length; i++) {
                        var leavingUser = self.onlineUsers.users[i];
                        if (leavingUser.id == userId) {
                            var nickName = leavingUser.nickname;
                            var avatar = leavingUser.avatar;
                            //Delete the outgoing users from online users
                            self.onlineUsers.users.splice(i, 1);
                            //Trigger interface update
                            self.onLeaveRoom(nickName, avatar);
                        }
                    }
                }
            });
        },
        onSuccess : function () {
            Console.log ("listening succeeded")
        },
        onFailed : function () {
            Console.log ("listening failed")
        }
    });
};

2. Send message

  • Initialize a chatmessage object, including sender ID, nickname, message content, and the message type is chat
  • Convert chatmessage to a string in JSON format
  • Call the publish method of goeasy to send the message

Reference code (service. JS)

this.sendMessage = function(content) {
    var message = new ChatMessage(this.currentUser.id,this.currentUser.nickname, MessageType.CHAT, content);
    var self = this;
    this.goeasy.publish({
        channel: self.currentRoomId,
        message: JSON.stringify(message),
        onSuccess: function() {
            Console.log ("message published successfully");
        },
        onFailed: function(error) {
            Console.log ("message sending failed, error code: + error. Code +" error message: + error. Content ");
        }
    });
};

3. Receive and display new messages / props

Previously, we have executed service. Subscribernewmessage () when initializing the page. When we receive a message:

  • Judge whether it is a chat message or a prop according to the message type
  • If you receive a chat message, it will be displayed directly to the interface
  • If it’s a prop, play the animation

Reference code (service. JS)

//Monitor messages or props
this.subscriberNewMessage = function() {
    var self = this;
    this.goeasy.subscribe({
        Channel: this.currentroomid, // replace with your own channel
        onMessage: function(message) {
            var chatMessage = JSON.parse(message.content);
            //Todo: in fact, it is not recommended to save messages when they are received by the front end. If a user opens multiple windows, it will lead to repeated saving. It is recommended that all messages be saved on the server when they are sent. This is just for demonstration
            self.restapi.saveChatMessage(self.currentRoomId, chatMessage);
            //If a message is received, it is displayed as a message
            if (chatMessage.type == MessageType.CHAT) {
                var selfSent = chatMessage.senderUserId == self.currentUser.id;
                var content = JSON.parse(message.content);
                self.onNewMessage(chatMessage.senderNickname, content, selfSent);
            }
            //If you receive a prop, play the prop animation
            if (chatMessage.type == MessageType.PROP) {
                if (chatMessage.content == Prop.ROCKET) {
                    self.onNewRocket(chatMessage.senderNickname);
                }
                if (chatMessage.content == Prop.HEART) {
                    self.onNewHeart(chatMessage.senderNickname);
                }
            }
        }
    });
};

4. Send, receive and display props

In fact, the implementation is almost the same as sending messages. Please refer to the sendprop method of service.js and the onnewheart () method of controller.js for the specific code. The library of tweenmax is used to play the animation, mainly to show an implementation idea. Xiaobian doesn’t know whether the library has good compatibility, and whether it can be used in uniapp and small programs. Friends who know can leave a message to share with you.

this.sendProp = function(prop) {
    var self = this;
    var message = new ChatMessage(this.currentUser.id,this.currentUser.nickname, MessageType.PROP, prop);
    this.goeasy.publish({
        channel: self.currentRoomId,
        message: JSON.stringify(message),
        onSuccess: function() {
            Console.log ("the prop was released successfully");
        },
        onFailed: function(error) {
            Console.log ("failed to send props, error code: + error. Code +" error message: + error. Content ");
        }
    });
};

So far, a chat room is done, isn’t it very simple?

If you have any questions during reading this article or developing, you are welcome to add goeasy as a friend on the official website of goeasy to get more technical support.

Goeasy website:www.goeasy.io/

Go easy series:

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Example of method for converting Lua table to c# dictionary

Table property Table is an “associative array”. The index of the array can be a number or a string. All index values need to be enclosed by “[” and “]”; If it is a string, you can also remove quotation marks and brackets; That is, if it is not enclosed by [], it is considered […]