Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to Open WebSocket Interface in SpringMVC

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to open the WebSocket interface in SpringMVC, the content is very detailed, interested friends can refer to, hope to be helpful to you.

1. Configure WebSocket interface information.

1) first create a websocket-specific package (specification problem, the source code to implement a function should be placed under a unified path).

2) create the WebSocketConfig class, inherit the WebMvcConfigurationSupport class, implement the WebSocketConfigurer interface and implement its defined methods. Add class comments

@ Configuration

@ EnableWebMvc

@ EnableWebSocket

3) in the implemented registerWebSocketHandlers method, the object with the parameter WebSocketHandlerRegistry opens the WebSocket interface.

Registry.addHandler (websocket message processing implementation class instance, websocket address). SetAllowedOrigins ("*"). AddInterceptors (interceptor instance)

SetAllowedOrigins is used to set access permissions, and "*" is usually used when access is not restricted; addInterceptors is to add interceptors, and this method can not be called if you do not need interceptors.

Usually there are two open WebSocket interfaces. Due to the problem supported by browsers, the front end can only use SockJS plug-ins to implement WebSocket connections, so we also need to open a WebSocket interface specifically for SockJS services, just call the withSockJS interface.

Registry.addHandler (websocket message processing implementation class instance, websocket address). SetAllowedOrigins ("*"). AddInterceptors (interceptor instance). WithSockJS ()

At this point, the first step is to configure the WebSocket information.

2. Customize the WebSocket message processing implementation.

1) create an WebSocket message handling interface and inherit the WebSocketHandler interface (it is an open operation interface to other services, which is generally related to business. This API is also related to specification and can be implemented in other ways when the server wants to push messages.

2) create the WebSocket message processing implementation class and implement the interface created in the first step. The business interfaces should be implemented by yourself. The APIs that inherit the implementation from WebSocketHandler are:

AfterConnectionEstablished: triggered when a WebSocket connection is established successfully.

HandleMessage: triggered when a message is received from the client.

HandleTransportError: triggered when an exception occurs.

AfterConnectionClosed: triggered when disconnected from the client.

SupportsPartialMessages: whether partial message processing is supported (generally, false is returned. This flag is generally used to split large or unknown WebSocket messages. When partial messages are supported, a message will be split into multiple messages to call handleMessage. You can use the isLast method of WebSocketMessage to determine whether it is the last message.

3. Custom WebSocket message interceptor (optional)

1) create a WebSocket interceptor to implement the HandshakeInterceptor interface. The implementation methods are as follows:

BeforeHandshake: before message processing.

AfterHandshake: after message processing.

4. Load the WebSocket configuration instance into the Spring container

In the form of a configuration scan package, add it to the configuration file

Base-package can be configured according to the actual package path of your project.

The following is the example code. The details can be modified according to the actual project:

WebSocket configuration Information

Package com.???.websocket;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowire;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer Import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;/** * websocket configuration class * * @ author Heller.Zhang * @ since 10:23:04 on November 8, 2018 * / @ Configuration@EnableWebMvc@EnableWebSocketpublic class MyWebSocketConfig extends WebMvcConfigurationSupport implements WebSocketConfigurer {private Logger logger = LoggerFactory.getLogger (MyWebSocketConfig.class) / * (non-Javadoc) * @ see org.springframework.web.socket.config.annotation.WebSocketConfigurer#registerWebSocketHandlers (org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry) * / @ Override public void registerWebSocketHandlers (WebSocketHandlerRegistry registry) {logger.debug ("- start registering MyWebSocketConfig-") Logger.debug ("- register ordinary websocket-"); registry.addHandler (msgSocketHandle (), "/ websocket/myWebSocketServer"). SetAllowedOrigins ("*"); logger.debug ("- register sockjs/websocket-") Registry.addHandler (msgSocketHandle (), "/ websocket/sockjs/myWebSocketServer") .setAllowedOrigins ("*") .withSockJS ();} @ Bean (name = "myMsgScoketHandle", autowire = Autowire.BY_NAME) public MyMsgScoketHandle msgSocketHandle () {return new MyMsgScoketHandleImpl ();}}

Customize the WebSocket message handling interface

Package com.???.websocket;import org.springframework.web.socket.WebSocketHandler;/** * websocket message processor * * @ author Heller.Zhang * @ since 5:13:20 13 November 2018 * / public interface MyMsgScoketHandle extends WebSocketHandler {public void sendMessage (Long userId, Integer num);}

Custom WebSocket message processing interface implementation

Package com.???.websocket;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import org.apache.commons.collections.CollectionUtils;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketMessage Import org.springframework.web.socket.WebSocketSession;import com.hzsparrow.framework.common.exception.ServiceException;import com.hzsparrow.framework.utils.JsonUtils;import com.hzsparrow.framework.utils.NumberUtils;/** * websocket message handling class * * @ author Heller.Zhang * @ since 11:15:22 on November 8, 2018 * / public class MyMsgScoketHandleImpl implements MyMsgScoketHandle {private Logger logger = LoggerFactory.getLogger (MyMsgScoketHandleImpl.class); private ConcurrentMap webSocketMap = new ConcurrentHashMap () Public MyMsgScoketHandleImpl () {logger.debug ("- init MyMsgScoketHandle-") } / * (non-Javadoc) * @ see org.springframework.web.socket.WebSocketHandler#afterConnectionEstablished (org.springframework.web.socket.WebSocketSession) * / @ Override public void afterConnectionEstablished (WebSocketSession session) throws Exception {logger.debug ("- establish websocket connection -") } / * (non-Javadoc) * @ see org.springframework.web.socket.WebSocketHandler#handleMessage (org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.WebSocketMessage) * / @ Override public void handleMessage (WebSocketSession session, WebSocketMessage message) throws Exception {logger.debug ("- processing messages -"); TextMessage msg = (TextMessage) message / / user id String msgStr= msg.getPayload () sent by establishing a connection; logger.debug ("- msg:" + msgStr); if (StringUtils.equals (msgStr, "heartbeat")) {/ / heartbeat message, return is not processed } session.getAttributes () .put ("mykey", msgStr + "|" + UUID.randomUUID () .toString ()); / / get the session collection List list = webSocketMap.get (msgStr) through the user id; / / determine whether the collection is empty if (CollectionUtils.isNotEmpty (list)) {list.add (session);} else {list = new ArrayList () List.add (session);} / / bind user id and session collections to map webSocketMap.put (msgStr, list); logger.debug ("message processed") } / * (non-Javadoc) * @ see org.springframework.web.socket.WebSocketHandler#handleTransportError (org.springframework.web.socket.WebSocketSession, java.lang.Throwable) * / @ Override public void handleTransportError (WebSocketSession session, Throwable exception) throws Exception {logger.debug ("- handle exception -") } / * (non-Javadoc) * @ see org.springframework.web.socket.WebSocketHandler#afterConnectionClosed (org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.CloseStatus) * / @ Override public void afterConnectionClosed (WebSocketSession session, CloseStatus closeStatus) throws Exception {logger.debug ("- disconnect -") String myKey = session.getAttributes (). Get ("mykey"). ToString (); String userId = myKey.split ("|") [0]; List list = webSocketMap.get (userId); WebSocketSession delSession = null; if (CollectionUtils.isNotEmpty (list)) {for (WebSocketSession webSocketSession: list) {String delKey = webSocketSession.getAttributes (). Get ("mykey"). ToString () If (StringUtils.equals (myKey, delKey)) {delSession = webSocketSession; break;} if (delSession! = null) {list.remove (delSession) }} / * (non-Javadoc) * @ see org.springframework.web.socket.WebSocketHandler#supportsPartialMessages () * / @ Override public boolean supportsPartialMessages () {return false } / * send a message to a single user * * @ param session * @ param type * @ param data * @ throws IOException * @ author Heller.Zhang * @ since 2:05:32 on November 8, 2018 * / public void sendMessage (WebSocketSession session Object data) throws IOException {if (session.isOpen ()) {String json = JsonUtils.serialize (data) TextMessage outMsg = new TextMessage (json); session.sendMessage (outMsg) }} / * send link success message * * @ param session * @ throws IOException * @ author Heller.Zhang * @ since 3:16:35 on November 10, 2018 * / public void sendSuccessMsg (WebSocketSession session Integer type) throws IOException {logger.debug ("- send link success message -") TextMessage outMsg = new TextMessage (""); session.sendMessage (outMsg);} @ Override public void sendMessage (Long userId, Integer num) {/ / get the session collection under the user List list = webSocketMap.get (NumberUtils.num2Str (userId)) / send data if (CollectionUtils.isNotEmpty (list)) {for (WebSocketSession webSocketSession: list) {try {sendMessage (webSocketSession, num);} catch (IOException e) {throw new ServiceException ("failed to send message") to each session }}}

Interceptor

Package com.???.websocket;import java.util.Map;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.HandshakeInterceptor / * websocket interceptor * * @ author Heller.Zhang * @ since 10:40:51 on November 8, 2018 * / public class MyWebSocketHandshakeInterceptor implements HandshakeInterceptor {private Logger logger = LoggerFactory.getLogger (MyWebSocketHandshakeInterceptor.class) / * (non-Javadoc) * @ see org.springframework.web.socket.server.HandshakeInterceptor#beforeHandshake (org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler, java.util.Map) * / @ Override public boolean beforeHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler Map attributes) throws Exception {logger.debug ("- websocket interceptor before handshake -") Return true } / * (non-Javadoc) * @ see org.springframework.web.socket.server.HandshakeInterceptor#afterHandshake (org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler, java.lang.Exception) * / @ Override public void afterHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler Exception exception) {logger.debug ("- websocket interceptor handshake -") }}

Scan package configuration

On how to open the WebSocket interface in SpringMVC to share here, I hope the above content can be of some help to you, you can learn more knowledge. If you think the article is good, you can share it for more people to see.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report