In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use HTML+JQuery to realize live room chat room". In daily operation, I believe many people have doubts about how to use HTML+JQuery to realize live room chat room. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use HTML+JQuery to realize live room chat room". Next, please follow the editor to study!
The chat room we are going to implement this time has two interfaces, which are:
Login Page
Chat room interface
Log in
For the login interface, we expect:
Users can enter their own nicknames
Users can choose the avatar they like.
Users can choose to enter different chat rooms (live rooms).
Implementation steps
The implementation of the login interface, needless to say, because it is really So Easy! A simple interface that contains only three simple logic:
Verify if you enter a nickname
Verify that an avatar is selected
Enter the corresponding chat room according to your choice
The following focuses on the implementation of chat rooms.
Chat room (live room)
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. The chat room will be prompted by "XXX is in" or "XXX is gone".
b. The number of online users and the list of users' avatars will be automatically updated.
Users can speak in chat.
Users can send props: rocket or Bixin.
Implementation step 1: chat room interface display
1. Initialize:
Before the user selects a chat room and displays the chat room interface, we need to do the following initialization work:
Initialize the current user currentUser, user id, nickname, avatar
Initialize the current chat room ID: currentRoomId
When initializing the GoEasy object, be sure to add the userId parameter (it can be a unique ID such as uuid or id of the user. Only when the client with userId is set up and offline, the online / offline reminder will be triggered). At the same time, we need to put the profile picture and nickname into userData, and when we receive a reminder that a user is online, we need to know the user's profile picture and nickname.
Initialization onlineUsers,onlineUsers is used to store the number of online users and the list of online users in the current chat room. Take the current chat room Id (currentRoomId) as the channel, execute goEasy.hereNow to query the current chat room online user number and user list, and assign a value to onlineUsers. In addition to initializing onlineUsers when entering a chat room, onlineUsers is also updated dynamically when a user enters or leaves.
Using the id (currentRoomId) of the current chat room as the channel, execute the subscriber method to listen and receive new chat room messages.
Use the id (currentRoomId) of the current chat room as the channel to execute subscriberPresence to listen for user entry and departure 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 current chat room id this.currentRoomId = roomID / / initialize goeasy Establish persistent 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 list of current online users and initialize the onlineUsers object this.initialOnlineUsers (); / / listen for user online and offline reminders to update the onlineUsers object this.subscriberPresence () in real time; / / listen and receive new messages this.subscriberNewMessage ();}
two。 The page is displayed:
After initialization, jump to the LVB room interface and display the following data on the page:
Name of the current chat room
Chat notes and display the chat room interface
Show the chat room interface
Reference code: controller.js
/ / 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) {/ / display the message sent var otherPerson = createCurrentChatRoomPerson (item.senderNickname + ", item.content) $(" .chatRoom-content-box "). Append ($(otherPerson)); / / hide the login interface $(" .chat-login-box "). Hide (); / / show chat interface $(" .chatRoom-box "). Show () / Slide to the last line scrollBottom ();}
At this point, we have completed the initialization of the goeasy persistent connection and a static display of a chat room. Next, let's take a look at how to get this chat room moving.
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, but users enter and exit the chat room at any time, so we need to be able to update the onlineUsers in real time when users are online or offline, and display it on the page in real time.
When we receive a user online reminder, we store the information of the new user in the online user object onlineUsers, and delete it from the local online user list when a user leaves.
Reference code: service.js
/ / monitor the user's online and offline 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 the number of onlineUsers online users self.onlineUsers.count = count; / / if users enter 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); / / trigger interface update self.onJoinRoom (user.nickname, user.avatar) } else {for (var I = 0; I < self.onlineUsers.users.length; iTunes +) {var leavingUser = self.onlineUsers.users [I]; if (leavingUser.id = = userId) {var nickName = leavingUser.nickname; var avatar = leavingUser.avatar / / delete self.onlineUsers.users.splice (I, 1) from onlineUsers for departing users; / / trigger the update self.onLeaveRoom of the interface (nickName, avatar) });}, onSuccess: function () {console.log ("Monitoring success")}, onFailed: function () {console.log ("Monitoring failure")});}
two。 Send a message
Initialize a chatMessage object containing the sender id, nickname, message content, and message type of 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 failed, error code:" + error.code + "error message:" + error.content);});}
3. Receive and display new messages / props
We have previously 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, display it directly to the interface.
If it's a prop, play the animation.
Reference Code (service.js)
/ / listen for 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 it is received at the front end. Multiple windows are opened by one user, which will lead to repeated saving. It is recommended that all messages be saved on the server side when they are sent. Here is just to demonstrate self.restapi.saveChatMessage (self.currentRoomId, chatMessage). / / if a message is received, it is displayed as 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, the implementation is almost the same as sending messages. For specific code, please refer to service.js 's sendProp method and controller.js 's onNewHeart () method. Animation playback, the use of the TweenMax library, mainly to show an implementation idea, the editor does not know whether this library has a good compatibility, and whether it can be used in Uniapp and Mini Program, friends who know can leave messages 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 ("props released successfully.") ;}, onFailed: function (error) {console.log ("props failed to send, error code:" + error.code + "error message:" + error.content);});}; at this point, the study on "how to use HTML+JQuery to implement live room chat rooms" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.