In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "WebSocket how to achieve server message push client", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "WebSocket how to achieve server message push client" this article.
I. background
The project needs to do a function that the message can be obtained in real time. The daily active volume of the system reaches 10000, and the message generated is several times of the active volume. If you use Http to poll the back-end service, it will make the back-end service collapse under too much pressure, so you need a new technical way to change the "pull" way.
II. Solutions
After a variety of Google, Baidu found that html5's new technology WebSocket can be used to change the existing "pull" message into a "push" mode, greatly reducing the pressure on the server.
III. Concrete realization
The example adopts Spring Boot framework.
Introduce pom dependency
Org.springframework.boot
Spring-boot-starter-websocket
Org.springframework.boot
Spring-boot-starter-undertow
Org.springframework.boot
Spring-boot-starter-web
Org.springframework.boot
Spring-boot-starter-tomcat
WebSocket services can be developed using websocket-api or spring-websocket, and we adopt the annotated development method of websocket-api:
Package com.gridsum.techpub.systemhistory.api.server
Import org.slf4j.Logger
Import org.slf4j.LoggerFactory
Import org.springframework.stereotype.Service
Import javax.websocket.*
Import javax.websocket.server.PathParam
Import javax.websocket.server.ServerEndpoint
Import java.io.IOException
Import java.util.Objects
Import java.util.Set
Import java.util.concurrent.CopyOnWriteArraySet
/ * *
* @ author ouyangrongtao
* @ version 1.0
* @ description WebSocketServer
* @ date 10:16 on 2019-12-23
* * /
@ ServerEndpoint ("/ websocket/ {sid}")
@ Service
Public class WebSocketServer {
Private static final Logger logger = LoggerFactory.getLogger (WebSocketServer.class)
Private ClientInfo clientInfo
/ * *
* store the corresponding ClientInfo object for each client.
* /
Private static final Set WEB_SOCKET_SET = new CopyOnWriteArraySet ()
/ * *
* the method called successfully when the connection is established
*
* @ param session session
* @ param sid client
* /
@ OnOpen
Public void onOpen (Session session, @ PathParam ("sid") String sid) {
/ / join set
This.clientInfo = new ClientInfo (sid, session)
WEB_SOCKET_SET.add (clientInfo)
Logger.info ("start listening with a new window: [{}], the current number of online users is [{}]", sid, WEB_SOCKET_SET.size ())
Try {
This.sendMessage (session, "connected successfully")
} catch (IOException e) {
Logger.error ("websocket IO exception")
}
}
/ * *
* connect the method called by closing the call
* /
@ OnClose
Public void onClose () {
/ / remove from set
WEB_SOCKET_SET.remove (this.clientInfo)
Logger.info ("one connection is closed! the current number of people online is: [{}]", WEB_SOCKET_SET.size ())
}
/ * *
*
Messages sent by * @ param message client
* /
@ OnMessage
Public void onMessage (String message) {
Logger.info ("received message from window [{}]: [{}]", this.clientInfo.getSid (), message)
/ / send a message
For (ClientInfo item: WEB_SOCKET_SET) {
Try {
This.sendMessage (item.getSession (), message)
} catch (IOException ignored) {
}
}
}
/ * *
* called in case of error
* @ param session session
* @ param error error message
* /
@ OnError
Public void onError (Session session, Throwable error) {
Logger.error ("error occurred", error)
}
/ * *
* send a message to sid
* @ param message message
* @ param sid sid
* /
Public void sendMessage (String message, String sid) {
Logger.info ("push message to window [{}], push content: [{}]", sid, message)
ClientInfo client = WEB_SOCKET_SET.parallelStream ()
.filter (item-> item.getSid () .equals (sid)) .findFirst () .orElse (null)
If (client! = null) {
Try {
This.sendMessage (client.getSession (), message)
} catch (IOException ignored) {
}
}
}
/ * *
* implement active push on the server
* @ param session session
* @ param message message
* @ throws IOException IOException
* / which gynecological hospital in Zhengzhou has a good http://www.sptdfk.com/
Private void sendMessage (Session session, String message) throws IOException {
Session.getBasicRemote () sendText (message)
}
Class ClientInfo {
/ * *
* receive sid
* /
Private String sid = ""
/ * *
* client
* /
Private Session session
Public ClientInfo () {}
Private ClientInfo (String sid, Session session) {
This.sid = sid
This.session = session
}
Private String getSid () {
Return sid
}
Private Session getSession () {
Return session
}
@ Override
Public boolean equals (Object o) {
If (this = = o) {
Return true
}
If (o = = null | | getClass ()! = o.getClass ()) {
Return false
}
ClientInfo that = (ClientInfo) o
Return Objects.equals (sid, that.sid)
}
@ Override
Public int hashCode () {
Return Objects.hash (sid)
}
}
}
Front-end code
Run WebSocketClient1000001
Come to an interface that sends messages.
/ * *
* send messages to the client
* @ author ouyangrongtao
* /
@ RestController
Public class WebSocketController {
Private WebSocketServer webSocketServer
@ Autowired
Public WebSocketController (WebSocketServer webSocketServer) {
This.webSocketServer = webSocketServer
}
@ PostMapping ("/ socket/push")
Public boolean pushToWeb (@ RequestBody Map content) {
WebSocketServer.sendMessage (content.get ("message"), content.get ("cid"))
Return true
}
}
So far, it has been basically finished. Using Postman to call the sending interface, it is found that the client can receive the sent message.
IV. Problem record
When doing this, because of the Tomcat container used in the project, there is a conflict between the Tomcat-related package and the WebSocket dependency, and the project cannot be started in the end. The solution is to change the Tomcat container to Undertow.
Org.springframework.boot
Spring-boot-starter-undertow
Org.springframework.boot
Spring-boot-starter-web
Org.springframework.boot
Spring-boot-starter-tomcat
Exception message:
Caused by: java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
At org.springframework.util.Assert.state (Assert.java:73)
At org.springframework.web.socket.server.standard.ServerEndpointExporter.afterPropertiesSet (ServerEndpointExporter.java:106)
At org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods (AbstractAutowireCapableBeanFactory.java:1753)
At org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1690)
... 16 common frames omitted
The above is all the contents of the article "how to implement the server message push client in WebSocket". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.