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

The implementation of spring WebSocket entry and interceptor

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "the implementation of spring WebSocket entry and interceptor". In daily operation, I believe many people have doubts about the implementation of spring WebSocket entrance and interceptor. Xiaobian 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 "spring WebSocket entry and interceptor implementation". Next, please follow the editor to study!

+

I. POM dependence

POM dependency, spring4.1.4.RELEASE,spring core dependency, please add it yourself. Here is the jar related to websocket.

Javax.websocket javax.websocket-api 1.0 provided org.springframework spring-websocket 4.1.4.RELEASE II, WebSocket entry @ Configuration@EnableWebMvc@EnableWebSocketpublic class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {@ Override public void registerWebSocketHandlers (WebSocketHandlerRegistry registry) {/ / allowed domains that can only start with http or https String [] allowsOrigins = {"http://www.xxx.com"}; / / WebIM WebSocket channel registry.addHandler (chatWebSocketHandler (), "/ webSocketIMServer") .setAllowedOrigins (allowsOrigins) .addInterceptors (myInterceptor ()); registry.addHandler (chatWebSocketHandler (), "/ sockjs/w ebSocketIMServer") .setAllowedOrigins (allowsOrigins) .addInterceptors (myInterceptor ()) .withSockJS ();} @ Bean public ChatWebSocketHandler chatWebSocketHandler () {return new ChatWebSocketHandler () @ Bean public WebSocketHandshakeInterceptor myInterceptor () {return new WebSocketHandshakeInterceptor ();}}

Implement the WebSocketConfigurer interface, override the registerWebSocketHandlers method, which is a core implementation, configure the websocket entry, allow access to the domain, register Handler, SockJs support, and interceptor.

The function of registry.addHandler registration and routing, when the client initiates a websocket connection and hands / path to the corresponding handler for processing, without implementing the specific business logic, can be understood as the collection and task distribution center.

SetAllowedOrigins (String [] domains), which allows a specified domain name or IP (including port number) to establish a persistent connection. If only your own domain name is allowed to access, it is easy to set up here. If you use the "*" sign for an unlimited time, if you specify a domain name, you must start with http or https.

AddInterceptors, as the name implies, is to add an interceptor to handler, and you can add our own logic code before and after calling handler.

Spring websocket also supports the STOMP protocol. We'll share it next time.

3. Interceptor implements public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {@ Override public boolean beforeHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {if (request instanceof ServletServerHttpRequest) {attributes.put ("username", userName);} return true;} @ Override public void afterHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {}}

BeforeHandshake, which handles the method before calling handler. It is often used to register user information, bind WebSocketSession, obtain WebSocketSession and send messages according to user information in handler.

4. Handler processing class public class ChatWebSocketHandler extends TextWebSocketHandler {private final static List sessions = Collections.synchronizedList (new ArrayList ()); / / receives text messages and sends out @ Override protected void handleTextMessage (WebSocketSession session, TextMessage message) throws Exception {chatTextMessageHandler (message.getPayload ()); super.handleTextMessage (session, message) } / / Post-connection processing @ SuppressWarnings ("unchecked") @ Override public void afterConnectionEstablished (WebSocketSession session) throws Exception {logger.debug ("connect to the websocket chat success."); sessions.add (session) / / handle offline messages} / / handle @ Override public void handleTransportError (WebSocketSession session, Throwable exception) throws Exception {if (session.isOpen ()) {session.close ();} logger.debug ("websocket chat connection closed."); sessions.remove (session) when throwing an exception } / / Post-processing @ Override public void afterConnectionClosed (WebSocketSession session, CloseStatus closeStatus) throws Exception {logger.debug ("websocket chat connection closed."); sessions.remove (session);} @ Override public boolean supportsPartialMessages () {return false;}} V. Client connection var host = _ window.location.host;var websocket If ('WebSocket' in window) {websocket = new ReconnectingWebSocket ("ws://" + host + "/ webSocketIMServer", null, {debug:true, maxReconnectAttempts:4});} else if (' MozWebSocket' in window) {websocket = new MozWebSocket ("ws://" + host + "/ webSocketIMServer");} else {websocket = new SockJS ("http://" + host +" / sockjs/webSocketIMServer ") } websocket.onopen = function (evnt) {console.log ("websocket connection");}; websocket.onmessage = function (evnt) {messageHandler (evnt.data);}; websocket.onerror = function (evnt) {console.log ("websocket error"); websocket.onclose = function (evnt) {console.log ("websocket off");}

ReconnectingWebSocket.js is used here, and extensions are added to the browser's own websocket, such as reconnection, connection timeout, failed reconnection interval, maximum number of connection attempts, and so on.

At this point, the study on "the implementation of spring WebSocket entry and interceptor" is over. I hope to be able to solve your 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.

Share To

Development

Wechat

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

12
Report