Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use webSocket to maintain long connection in Spring MVC

Shulou Source: shulou.com Published: 2022-06-02 10:15:37 11月08日 Update

This article is to share with you about how to use webSocket to maintain a long connection in Spring MVC. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Configuration

Add package dependencies to pom.xml

Javax javaee-api 7.0 provided org.springframework spring-websocket 4.3.13.RELEASE

Java background implementation code

Package com.netcar.tien.mobile;import java.io.IOException;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import org.springframework.web.socket.server.standard.SpringConfigurator;import com.netcar.tien.core.log.LogFactory;import com.netcar.tien.core.log.OnlineLog / * keep socket connection * @ author JoyoDuan * Add by JoyoDuan on 2018-02-22 * * @ ServerEndpoint comment is a class-level annotation Its main function is to define the current class as a websocket server, * the value of the note will be used to listen for the terminal access URL address of the user connection, and the client can connect to the WebSocket server through this URL * / @ ServerEndpoint (value= "/ app/webSocket", configurator = SpringConfigurator.class) public class WebSocket {private OnlineLog logger = LogFactory.getOnlineLog (WebSocket.class) / / socket connection session, used to send a message to the client private Session session;/ * * client connected successfully * @ param session * @ throws IOException * / @ OnOpen public void onOpen (Session session) throws IOException {this.session = session;// System.out.println ("WebSocket connected successfully") Logger.info ("WebSocket-connected successfully"); execute * @ param message * @ param session * @ throws IOException * / @ OnMessage public void onMessage (String message, Session session) throws IOException {this.sendMessage ("success") when receiving the message Execute * / @ OnClose public void onClose () {logger.info ("webSocket-connection closed"); / / System.out.println ("webSocket connection closed") when closed } / * execute * @ param session * @ param error * / @ OnError public void onError (Session session, Throwable error) {logger.error ("webSocket-error:" + error.getMessage ()); / / System.out.println ("webSocket error" + error) } / * send a message to client * @ param message * @ throws IOException * / public void sendMessage (String message) throws IOException {this.session.getBasicRemote () .sendText (message);}}

The front end uses webSocket code

/ * maintain a long connection with the server * @ param {boolean} [isReconnect] * @ returns * @ memberof HomePage * / connectWebSocket (isReconnect?: boolean) {let webSocket = new WebSocket (this.urlService.getWebSocketURL ()); / / webSocket this.globalData.isLog & & console.log ('WebSocket:',' WebSocket' in window); / / timer for upload longitude and latitude let uploadLngLatTimer: number = null If (! isReconnect & &! ('WebSocket' in window)) {/ / this.nativeService.alert (' your phone does not support location upload'); return;} / / Monitoring network disconnection this.nativeService.monitorNetworkDisconnect (() = > {this.nativeService.toast ('dear, network connection is broken'); / / Recursive, reconnect this.connectWebSocket (true); return;}) / / initialize webSocket webSocket.onopen = (event) = > {this.globalData.isLog & &! isReconnect & & console.log ('webSocket-connected to the server successfully!', event); this.globalData.isLog & & isReconnect & & console.log ('webSocket-reconnect to the server!', event) / / upload latitude and longitude every 10 seconds uploadLngLatTimer = setInterval (() = > {/ / upload longitude and latitude this.getAMapLocationByJS (true,) = > {/ / webSocket.send ('JoyoDuan' + new Date (). GetTime () Let params = {strokeNo: this.trip.strokeNo, strokeStatus: this.trip.strokeStatus, strokeLongitude: this.position.currentPosition.lngLat.lng, strokeLatitude: this.position.currentPosition.lngLat.lat, routeId: this.trip.routeId, carTypeId: this.trip.carTypeId | |'} / / send latitude and longitude to the server webSocket.send (Secret.encodeBase64String (JSON.stringify (params); this.globalData.isLog & & console.log ('webSocket-real-time upload latitude and longitude transmission parameters:', JSON.stringify (params));});}, TIMEOUT.UPLOAD_LNGLAT_TIMEOUT);} / / execute webSocket.onclose = () = > {this.globalData.isLog & & console.log ('webSocket-connection server shuts down!', event) when the connection is closed; / / clear the timer and stop sending clearInterval (uploadLngLatTimer);} / / execute webSocket.onerror = (event) = > {this.globalData.isLog & & console.log ('webSocket-connection server error!', event); / / reconnect setTimeout in 10 seconds (() = > {this.connectWebSocket (true);}, TIMEOUT.RECONNECT_WEB_SOCKET);} / / execute webSocket.onmessage = (event) = > {this.globalData.isLog & & console.log ('webSocket-message sent by the server!' when you receive the server message , event);}} above is how to use webSocket to maintain a long connection in Spring MVC. 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.

Tags: Server service message latitude and longitude longitude and latitude success client client comment error code location more knowledge article network utility front end function parameter Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Huawei Shulou Technology Linux Microsoft