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 implement an application with webSocket and spring

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

Share

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

This article is about how to use webSocket and spring to achieve an application, the editor feels very practical, so share with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.

1.spring-websocket dependency package

4.0.2.RELEASE

Org.springframework

Spring-websocket

${spring.version}

Org.springframework

Spring-messaging

${spring.version}

2 sping profile

Where the namespace

Xmlns:websocket= "http://www.springframework.org/schema/websocket"

And the features introduced

Http://www.springframework.org/schema/websocket

Http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd

3. Inherit TextWebSocketHandlerpackage com.gaofei.controller;import java.util.Timer;import java.util.TimerTask;import org.apache.log4j.Logger;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler;public class WebsocketEndPoint extends TextWebSocketHandler {private Timer timer; private Logger logger=Logger.getLogger (WebsocketEndPoint.class) @ Override protected void handleTextMessage (http request message TextMessage message in WebSocketSession session,//session) throws Exception {/ / after receiving the message, respond to the message and process the text message TextMessage returnMessage=new TextMessage ("the server returns message:" + message.getPayload ()); session.sendMessage (returnMessage) / / the server sends the front-end request information back to the browser super.handleTextMessage (session, message);} @ Override public void afterConnectionEstablished (WebSocketSession session) throws Exception {/ / after the handshake is successful, start a timer timer logger.info ("connection establishment post-processing method"); timer=new Timer (true) LoadDataTask task=new LoadDataTask (session); timer.schedule (task,1000,1000); / / 1s execute a task super.afterConnectionEstablished (session) } @ Override public void handleTransportError (WebSocketSession session, Throwable exception) throws Exception {logger.info ("handling method when throwing an exception"); super.handleTransportError (session, exception) } @ Override public void afterConnectionClosed (WebSocketSession session, CloseStatus status) throws Exception {/ / logger.info after connection is closed ("connection closed"); timer.cancel (); logger.info ("post-processing method for connection closure") Super.afterConnectionClosed (session, status);} / / the inner class implements data acquisition class LoadDataTask extends TimerTask {private WebSocketSession session; public WebSocketSession getSession () {return session } public void setSession (WebSocketSession session) {this.session = session;} public LoadDataTask () {super () } public LoadDataTask (WebSocketSession session) {/ / the system passes the currently connected session to the session of the inner class to achieve session sharing super (); this.session = session } @ Override public void run () {/ / start multithreaded int item0; String taskCommand= "scheduled execution of tasks" + + i; TextMessage textMessage = new TextMessage (taskCommand) Try {handleTextMessage (session, textMessage); / / call the handleTextMessage method regularly to send information} catch (Exception e) {e.printStackTrace () to the front end. Logger.error (e.getMessage (), e);} 4. Inherit HttpSessionHandshakeInterceptorpackage com.gaofei.controller;import java.util.Map;import org.apache.log4j.Logger;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;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;/** * interceptor (handshake) * / public class HandInterceptor extends HttpSessionHandshakeInterceptor {private Logger logger=Logger.getLogger (HandshakeInterceptor.class) @ Override public void afterHandshake (ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {logger.info ("after creating handshake..."); super.afterHandshake (request, response, wsHandler, ex) } @ Override public boolean beforeHandshake (ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Map arg3) throws Exception {logger.info ("before the handshake is complete"); return super.beforeHandshake (arg0, arg1, arg2, arg3);}} 5. Service registration annotation mode: package com.gaofei.controller;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry @ Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {@ Override public void registerWebSocketHandlers (WebSocketHandlerRegistry registry) {/ / support websocket registry.addHandler (new WebsocketEndPoint (), "/ websocket/socketServer.do") .addInterceptors (new HandInterceptor ()); / / support sockjs registry.addHandler (new WebsocketEndPoint (), "/ sockjs/socketServer.do") .addInterceptors (new HandInterceptor ()). WithSockJS () }}

Note: this class needs to be placed under the SpringMVC scan path.

@ Configuration indicates that this class is a Spring configuration class

@ EnableWebSocket declares that the class supports WebSocket

Note: there are many articles on the Internet that add an annotation @ EnableWebMvc and inherit WebMvcConfigurerAdapter, in which the @ EnableWebMVC annotation is used to turn on WebMVC configuration support. Equivalent to the elements used in DispatcherServlet context, the WebMvcConfigurerAdapter configuration class is actually a configuration mode within Spring, which uses the form of JavaBean instead of the traditional xml configuration file to customize the framework.

XML configuration mode:

6. Page WebSocket// loads websocket data function WebSocketTest () {if ("WebSocket" in window) {alert ("your browser supports WebSocket!"); / / Open a websocket var ws = new WebSocket ("ws://localhost:8080/webSocketServer/websocket/socketServer.do") Ws.onopen = function () {/ / Web Socket is connected, use the send () method to send data ws.send ("send data"); alert ("data sending...");}; ws.onmessage = function (evt) {var received_msg = evt.data Console.log (received_msg);}; ws.onclose = function () {/ / close websocket alert ("connection closed...");} }} running WebSocket above is how to use webSocket and spring to implement an application. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.

Share To

Internet Technology

Wechat

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

12
Report