生活随笔
收集整理的這篇文章主要介紹了
Spring MVC使用webSocket保持长连接
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
說(shuō)明
客戶端需要與服務(wù)器保持長(zhǎng)連接
配置
<!-- webSocket start Add by zhangxueliang 2019-02-22 --><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version><scope>provided</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-websocket</artifactId><version>4.3.13.RELEASE</version></dependency><!-- webSocket end -->
- Java后臺(tái)實(shí)現(xiàn)代碼
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;/*** 保持socket連接* @author JoyoDuan* Add by JoyoDuan on 2018-02-22* * @ServerEndpoint 注解是一個(gè)類層次的注解,它的功能主要是將目前的類定義成一個(gè)websocket服務(wù)器端,* 注解的值將被用于監(jiān)聽用戶連接的終端訪問URL地址,客戶端可以通過這個(gè)URL來(lái)連接到WebSocket服務(wù)器端*/
@ServerEndpoint(value="/app/webSocket", configurator = SpringConfigurator.class)
public class WebSocket {private OnlineLog logger = LogFactory.getOnlineLog(WebSocket.class);//socket連接會(huì)話,用于發(fā)送消息給客戶端private Session session;/*** 客戶端連接成功* @param session* @throws IOException*/@OnOpenpublic void onOpen(Session session) throws IOException {this.session = session;
// System.out.println("WebSocket連接成功");logger.info("WebSocket - 連接成功");}/*** 收到消息時(shí)執(zhí)行* @param message* @param session* @throws IOException*/@OnMessage public void onMessage(String message, Session session) throws IOException { this.sendMessage("success");}/*** 關(guān)閉時(shí)執(zhí)行*/@OnClosepublic void onClose() { logger.info("webSocket - 連接關(guān)閉");
// System.out.println("webSocket連接關(guān)閉");}/*** 連接錯(cuò)誤時(shí)執(zhí)行* @param session* @param error*/@OnError public void onError(Session session, Throwable error) {logger.error("webSocket - 出錯(cuò):" + error.getMessage());
// System.out.println("webSocket出錯(cuò)" + error);}/*** 發(fā)送消息給客戶端* @param message* @throws IOException*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}
}
/*** 與服務(wù)器保持長(zhǎng)連接* @param {boolean} [isReconnect]* @returns* @memberof HomePage*/connectWebSocket(isReconnect?: boolean){let webSocket = new WebSocket(this.urlService.getWebSocketURL()); ///webSocketthis.globalData.isLog && console.log('WebSocket:', 'WebSocket' in window);//上傳經(jīng)緯度的定時(shí)器let uploadLngLatTimer: number = null;if (!isReconnect && !('WebSocket' in window)){// this.nativeService.alert('您的手機(jī)不支持位置上傳');return;}//監(jiān)測(cè)網(wǎng)絡(luò)斷開this.nativeService.monitorNetworkDisconnect(() => {this.nativeService.toast('親,網(wǎng)絡(luò)連接中斷了');//遞歸,重新連接this.connectWebSocket(true);return;});//初始化webSocketwebSocket.onopen = (event) => {this.globalData.isLog && !isReconnect && console.log('webSocket - 連接服務(wù)器成功!', event);this.globalData.isLog && isReconnect && console.log('webSocket - 重新連接服務(wù)器!', event);//每隔10秒上傳一次經(jīng)緯度uploadLngLatTimer = setInterval(() => {//上傳經(jīng)緯度時(shí)定位當(dāng)前位置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 || ''};//發(fā)送經(jīng)緯度到服務(wù)器webSocket.send(Secret.encodeBase64String(JSON.stringify(params)));this.globalData.isLog && console.log('webSocket - 實(shí)時(shí)上傳經(jīng)緯度發(fā)送參數(shù):', JSON.stringify(params));});}, TIMEOUT.UPLOAD_LNGLAT_TIMEOUT);};//連接關(guān)閉時(shí)執(zhí)行webSocket.onclose = () => {this.globalData.isLog && console.log('webSocket - 連接服務(wù)器關(guān)閉!', event);//清除計(jì)時(shí)器,停止發(fā)送clearInterval(uploadLngLatTimer);};//連接出現(xiàn)錯(cuò)誤時(shí)執(zhí)行webSocket.onerror = (event) => {this.globalData.isLog && console.log('webSocket - 連接服務(wù)器錯(cuò)誤!', event);//10秒重連一次setTimeout(() => {this.connectWebSocket(true);}, TIMEOUT.RECONNECT_WEB_SOCKET);};//收到服務(wù)器消息時(shí)執(zhí)行webSocket.onmessage = (event) => {this.globalData.isLog && console.log('webSocket - 服務(wù)器發(fā)送的消息!', event);}}
總結(jié)
以上是生活随笔為你收集整理的Spring MVC使用webSocket保持长连接的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。