Spring MVC使用webSocket保持长连接
2018-05-12 本文已影响0人
JoyoDuan
说明
客户端需要与服务器保持长连接
配置
- 在
pom.xml
中加入包依赖
<!-- webSocket start Add by JoyoDuan on 2018-02-22 -->
<!-- webSocket start Add by JoyoDuan on 2018-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后台实现代码
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 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint(value="/app/webSocket", configurator = SpringConfigurator.class)
public class WebSocket {
private OnlineLog logger = LogFactory.getOnlineLog(WebSocket.class);
//socket连接会话,用于发送消息给客户端
private Session session;
/**
* 客户端连接成功
* @param session
* @throws IOException
*/
@OnOpen
public void onOpen(Session session) throws IOException
{
this.session = session;
// System.out.println("WebSocket连接成功");
logger.info("WebSocket - 连接成功");
}
/**
* 收到消息时执行
* @param message
* @param session
* @throws IOException
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException
{
this.sendMessage("success");
}
/**
* 关闭时执行
*/
@OnClose
public void onClose()
{
logger.info("webSocket - 连接关闭");
// System.out.println("webSocket连接关闭");
}
/**
* 连接错误时执行
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error)
{
logger.error("webSocket - 出错:" + error.getMessage());
// System.out.println("webSocket出错" + error);
}
/**
* 发送消息给客户端
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException
{
this.session.getBasicRemote().sendText(message);
}
}
- 前端使用webSocket代码
/**
* 与服务器保持长连接
* @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);
//上传经纬度的定时器
let uploadLngLatTimer: number = null;
if (!isReconnect && !('WebSocket' in window))
{
// this.nativeService.alert('您的手机不支持位置上传');
return;
}
//监测网络断开
this.nativeService.monitorNetworkDisconnect(() => {
this.nativeService.toast('亲,网络连接中断了');
//递归,重新连接
this.connectWebSocket(true);
return;
});
//初始化webSocket
webSocket.onopen = (event) => {
this.globalData.isLog && !isReconnect && console.log('webSocket - 连接服务器成功!', event);
this.globalData.isLog && isReconnect && console.log('webSocket - 重新连接服务器!', event);
//每隔10秒上传一次经纬度
uploadLngLatTimer = setInterval(() => {
//上传经纬度时定位当前位置
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 || ''
};
//发送经纬度到服务器
webSocket.send(
Secret.encodeBase64String(JSON.stringify(params))
);
this.globalData.isLog && console.log('webSocket - 实时上传经纬度发送参数:', JSON.stringify(params));
});
}, TIMEOUT.UPLOAD_LNGLAT_TIMEOUT);
};
//连接关闭时执行
webSocket.onclose = () => {
this.globalData.isLog && console.log('webSocket - 连接服务器关闭!', event);
//清除计时器,停止发送
clearInterval(uploadLngLatTimer);
};
//连接出现错误时执行
webSocket.onerror = (event) => {
this.globalData.isLog && console.log('webSocket - 连接服务器错误!', event);
//10秒重连一次
setTimeout(() => {
this.connectWebSocket(true);
}, TIMEOUT.RECONNECT_WEB_SOCKET);
};
//收到服务器消息时执行
webSocket.onmessage = (event) => {
this.globalData.isLog && console.log('webSocket - 服务器发送的消息!', event);
}
}