Webcock live chat room tutorial go easy quick realization of chat room

Time:2020-6-25

That fire has been broadcast live in the last two years. It’s really indescribable! Often a friend asks, I want to realize a live chat or I want to develop a chat room, how to start?

live-chatroom.gif

Today, Xiaobian will teach you how to make a chat room with go easy, which can also be used for the interaction in the live room. The full set of source code has been open-source, GIT address: https://gitee.com/goeasy-io/GoEasyDemo-Live-Chatroom.git

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, the HTML + jQuery method 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 want to realize this time has two interfaces, namely:

  • Login interface
  • Chat room interface

Sign in

login.png

For the login interface, we expect:

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

Implementation steps

The implementation of login interface, needless to say, is really so easy! A simple interface, only contains three simple logic:

Verify that the nickname is entered

Verify that a avatar is selected

Enter the corresponding chat room according to the selection

Next, I will focus on the realization of chat room.

Chat room (Live Room)

liveroom.png

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. There will be a prompt in the chat room that “XXX has come in” or “XXX has left”
  • b. The number of online users and the list of their avatars are automatically updated
  • Users can speak in chat
  • Users can send props: rockets or heart comparison

Implementation steps

Step 1: chat interface display

1. Initialization:

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

  • Initialize current user, user ID, nickname, Avatar
  • Initialize current room ID: currentroomid
  • Initialize the goeasy object, and 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 userid 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. Onlineusers is used to store the number of current chat room online users and the list of online users. Take the current room ID (currentroomid) as the channel and execute goEasy.hereNow Query the number of chat online users and the list of users at the moment, and assign the value to onlineusers. In addition to initializing onlineusers when entering the chat room, when a user enters or leaves, the onlineusers will also be updated dynamically.
  • Take the ID (currentroomid) of the current chat room as the channel, execute the subscriber method to listen for and receive new chat messages.
  • With the current room ID as the channel, execute subscriberpresence to listen for user 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 ID
  this.currentRoomId = roomID;
  //Initialize go easy and establish 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 the online and offline reminders of users and update the onlineusers object in real time
  this.subscriberPresence();
  //Listening and receiving new messages
  this.subscriberNewMessage();
};

2. Page display:

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

  • Name of the current chat room
  • Chat record and show chat interface
  • Show chat interface

Reference code: controller.js

//Page switch to chat 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();
 //// show chat interface
 $(".chatRoom-box").show();
 //// slide to the last line
 scrollBottom();
}

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

Step 2: chat room interaction
1. Real time update of online users and avatar list

Before service.initialOnlineUsers Method has initialized the onlineusers object, 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 online user object onlineusers, and delete it in the local online user list when any user leaves.

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 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 onlineusers list
     self.onlineUsers.users.push(user);
     //Update of trigger interface
     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 left users from onlineusers
       self.onlineUsers.users.splice(i, 1);
       //Update of trigger interface
       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 message type chat
  • Convert chatmessage to a string in JSON format
  • Call the publish method of goeasy to finish sending 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

We’ve already executed it when initializing the page service.subscriberNewMessage (), 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 directly displayed in 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 when the front end receives. A user opens multiple windows, which will result in repeated saving. It is recommended that all messages be saved on the server side 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 and receive and display props

In fact, it is almost the same as the implementation of sending messages. Please refer to the specific code service.js The sendprop method of, controller.js The onnewheart () method of. The use of tweenmax library for animation playing is mainly to show an implementation idea. Xiaobian also 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 messages and share them 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 props were released successfully. "";
  },
  onFailed: function(error) {
   console.log ("item sending failed, error code:"+ error.code  +Error message:+ error.content );
  }
 });
};

At this point, a chat room is done, isn’t it very simple?

summary

This is the introduction of this article about the quick implementation of chat room in go easy, a tutorial about live chat room in websocket. For more information about the content of websocket chat room, please search the previous articles of developepaer or continue to browse the following articles. I hope you can support developepaer in the future!