In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to achieve online chat with SpringBoot+WebSocket". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to chat online with SpringBoot+WebSocket.
Online chat is implemented by SpringBoot+WebSocket. In order to ensure the privacy of users, all chat data are saved locally in the system, and the server only forwards the data. OK, next, let's take a look at the general implementation steps.
Server side
The server first adds the websocket dependency, as follows:
Org.springframework.boot spring-boot-starter-websocket
Create a configuration class for WebSocket, as follows:
@ Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {@ Override public void registerStompEndpoints (StompEndpointRegistry stompEndpointRegistry) {stompEndpointRegistry.addEndpoint ("/ ws/endpointChat") .withSockJS ();} @ Override public void configureMessageBroker (MessageBrokerRegistry registry) {registry.enableSimpleBroker ("/ queue", "/ topic");}}
Instead of using the native websocket protocol here, I use stomp, a sub-protocol of websocket, which is more convenient. Message agents use both / queue and / topic, mainly because I have both point-to-point single chat (queue) and group chat (topic) that sends system messages.
Create the websocket processing class Controller, as follows:
@ Controllerpublic class WsController {@ Autowired SimpMessagingTemplate messagingTemplate; @ MessageMapping ("/ ws/chat") public void handleChat (Principal principal, String msg) {String destUser = msg.substring (msg.lastIndexOf (";") + 1, msg.length (); String message = msg.substring (0, msg.lastIndexOf (";)); messagingTemplate.convertAndSendToUser (destUser," / queue/chat ", new ChatResp (message, principal.getName ());}}
The message protocol is simple: the message sent is the last, followed by which user the message is to be sent to, which is extracted by string interception. The response message contains two fields, one is the content of the message, and the other is who sent the message.
OK, after that, our server has written it. It's very simple.
Front end
Front-end code is slightly complex, here I mainly introduce my general ideas and core code with partners, specific code partners can star source code for research.
First of all, when the user logs in successfully, I initiate a connection to websocket and connect the ws. The code of ws is mainly written in store, as follows:
Connect (context) {context.state.stomp = Stomp.over (new SockJS ("/ ws/endpointChat")); context.state.stomp.connect ({}, frame= > {context.state.stomp.subscribe ("/ user/queue/chat", message= > {var msg = JSON.parse (message.body); var oldMsg = window.localStorage.getItem (context.state.user.username + "#" + msg.from); if (oldMsg = null) {oldMsg = [] OldMsg.push (msg); window.localStorage.setItem (context.state.user.username + "#" + msg.from, JSON.stringify (oldMsg))} else {var oldMsgJson = JSON.parse (oldMsg); oldMsgJson.push (msg) Window.localStorage.setItem (context.state.user.username + "#" + msg.from, JSON.stringify (oldMsgJson))} if (msg.from! = context.state.currentFriend.username) {context.commit ("addValue2DotMap", "isDot#" + context.state.user.username + "#" + msg.from) } / / Update msgList var oldMsg2 = window.localStorage.getItem (context.state.user.username + "#" + context.state.currentFriend.username); if (oldMsg2 = = null) {context.commit ('updateMsgList', []);} else {context.commit (' updateMsgList', JSON.parse (oldMsg2);}});}, failedMsg= > {});}
After the connection is successful, you can prepare to receive the message from the server. After receiving the message from the server, the data is saved in localStorage in the format of current user name # message sender user name: [{from:' message sender', msg:' message content'}], followed by a json array The reason why the entire stored key uses the current user name # message sender user name is to avoid data confusion caused by multiple users logging in the same browser, OK, so that the chat records of the two people will be saved in this array. On the chat display page, it is automatically updated when the data in the array changes.
On the chat page, send a message via stomp, as follows:
This.$store.state.stomp.send ("/ ws/chat", {}, this.msg + ";" + this.currentFriend.username)
Note that the content of each message should not only include the content itself, but also add the name of the current sender.
You can update the chat page after each successful send. Update the chat page code as follows:
{{msg.msg}} {{msg.msg}}
If the value of the from field in the message is the user name of the current chat, it is the message sent, otherwise it is the message sent out, and different messages can be set in different styles.
At this point, I believe you have a deeper understanding of "how to achieve online chat with SpringBoot+WebSocket". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.