Browse Source

1.ws添加token校验

2.修复消息撤回异常bug
3.部分代码优化
master
xie.bx 3 years ago
parent
commit
59fb9e40cd
  1. 15
      im-client/src/main/java/com/bx/imclient/IMClient.java
  2. 5
      im-client/src/main/java/com/bx/imclient/sender/IMSender.java
  3. 6
      im-commom/pom.xml
  4. 3
      im-commom/src/main/java/com/bx/imcommon/contant/Constant.java
  5. 2
      im-commom/src/main/java/com/bx/imcommon/model/HeartbeatInfo.java
  6. 2
      im-commom/src/main/java/com/bx/imcommon/model/LoginInfo.java
  7. 18
      im-commom/src/main/java/com/bx/imcommon/util/JwtUtil.java
  8. 7
      im-platform/pom.xml
  9. 23
      im-platform/src/main/java/com/bx/implatform/config/JwtProperties.java
  10. 1
      im-platform/src/main/java/com/bx/implatform/config/MinIoClientConfig.java
  11. 4
      im-platform/src/main/java/com/bx/implatform/contant/Constant.java
  12. 2
      im-platform/src/main/java/com/bx/implatform/enums/ResultCode.java
  13. 18
      im-platform/src/main/java/com/bx/implatform/interceptor/AuthInterceptor.java
  14. 2
      im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java
  15. 7
      im-platform/src/main/java/com/bx/implatform/service/impl/PrivateMessageServiceImpl.java
  16. 58
      im-platform/src/main/java/com/bx/implatform/service/impl/UserServiceImpl.java
  17. 7
      im-platform/src/main/resources/application.yml
  18. 24
      im-server/src/main/java/com/bx/imserver/netty/processor/LoginProcessor.java
  19. 6
      im-server/src/main/resources/application.yml
  20. 25
      im-ui/src/api/wssocket.js
  21. 7
      im-ui/src/view/Home.vue

15
im-client/src/main/java/com/bx/imclient/IMClient.java

@ -12,13 +12,20 @@ import java.util.List;
@Configuration
public class IMClient {
@Autowired
private MessageListenerMulticaster listenerMulticaster;
@Autowired
private IMSender imSender;
/**
* 发送私聊消息
* 判断用户是否在线
*
* @param userId 用户id
*/
public Boolean isOnline(Long userId){
return imSender.isOnline(userId);
}
/**
* 发送私聊消息发送结果通过MessageListener接收
*
* @param recvId 接收用户id
* @param messageInfo 消息体将转成json发送到客户端
@ -28,7 +35,7 @@ public class IMClient {
}
/**
* 发送群聊消息
* 发送群聊消息发送结果通过MessageListener接收
*
* @param recvIds 群聊用户id列表
* @param messageInfo 消息体将转成json发送到客户端

5
im-client/src/main/java/com/bx/imclient/sender/IMSender.java

@ -107,4 +107,9 @@ public class IMSender {
}
}
}
public Boolean isOnline(Long userId){
String key = RedisKey.IM_USER_SERVER_ID + userId;
return redisTemplate.hasKey(key);
}
}

6
im-commom/pom.xml

@ -53,5 +53,11 @@
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!-- 引入操作JWT的相关依赖 -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.11.0</version>
</dependency>
</dependencies>
</project>

3
im-commom/src/main/java/com/bx/imcommon/contant/Constant.java

@ -7,4 +7,7 @@ public class Constant {
public static final long ONLINE_TIMEOUT_SECOND = 600;
// 消息允许撤回时间 300s
public static final long ALLOW_RECALL_SECOND = 300;
}

2
im-commom/src/main/java/com/bx/imcommon/model/HeartbeatInfo.java

@ -4,6 +4,4 @@ import lombok.Data;
@Data
public class HeartbeatInfo {
private long userId;
}

2
im-commom/src/main/java/com/bx/imcommon/model/LoginInfo.java

@ -5,5 +5,5 @@ import lombok.Data;
@Data
public class LoginInfo {
private long userId;
private String accessToken;
}

18
im-platform/src/main/java/com/bx/implatform/util/JwtUtil.java → im-commom/src/main/java/com/bx/imcommon/util/JwtUtil.java

@ -1,16 +1,17 @@
package com.bx.implatform.util;
package com.bx.imcommon.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import java.util.Date;
import com.auth0.jwt.exceptions.JWTVerificationException;
import java.util.Date;
public class JwtUtil {
/**
* 生成jwt字符串30分钟后过期 JWT(json web token)
* 生成jwt字符串 JWT(json web token)
* @param userId
* @param info
* @param expireIn
@ -26,12 +27,11 @@ public class JwtUtil {
.withAudience(userId.toString())
//存放自定义数据
.withClaim("info", info)
//五分钟后token过期
//过期时间
.withExpiresAt(date)
//token的密钥
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@ -70,11 +70,13 @@ public class JwtUtil {
* @return
* */
public static boolean checkSign(String token,String secret) {
try{
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
//.withClaim("username, username)
.build();
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
}catch (JWTVerificationException e) {
return false;
}
}
}

7
im-platform/pom.xml

@ -106,12 +106,7 @@
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 引入操作JWT的相关依赖 -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.11.0</version>
</dependency>
</dependencies>
<build>

23
im-platform/src/main/java/com/bx/implatform/config/JwtProperties.java

@ -0,0 +1,23 @@
package com.bx.implatform.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class JwtProperties {
@Value("${jwt.accessToken.expireIn}")
private Integer accessTokenExpireIn;
@Value("${jwt.accessToken.secret}")
private String accessTokenSecret;
@Value("${jwt.refreshToken.expireIn}")
private Integer refreshTokenExpireIn ;
@Value("${jwt.refreshToken.secret}")
private String refreshTokenSecret;
}

1
im-platform/src/main/java/com/bx/implatform/config/MinIoClientConfig.java

@ -8,6 +8,7 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class MinIoClientConfig {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accessKey}")

4
im-platform/src/main/java/com/bx/implatform/contant/Constant.java

@ -8,13 +8,13 @@ public class Constant {
public static final long MAX_FILE_SIZE = 10*1024*1024;
// 群聊最大人数
public static final long MAX_GROUP_MEMBER = 500;
// accessToken 过期时间(1小时)
// accessToken 过期时间(小时)
public static final Integer ACCESS_TOKEN_EXPIRE = 30 * 60;
// refreshToken 过期时间(7天)
public static final Integer REFRESH_TOKEN_EXPIRE = 7 * 24 * 60 * 60 ;
// accessToken 加密秘钥
public static final String ACCESS_TOKEN_SECRET = "MIIBIjANBgkq";
// refreshToken 加密秘钥
public static final String ACCESS_TOKEN_SECRET = "MIIBIjANBgkq";
public static final String REFRESH_TOKEN_SECRET = "IKDiqVmn0VFU";
}

2
im-platform/src/main/java/com/bx/implatform/enums/ResultCode.java

@ -10,7 +10,7 @@ package com.bx.implatform.enums;
public enum ResultCode {
SUCCESS(200,"成功"),
NO_LOGIN(400,"未登录"),
INVALID_TOKEN(401,"token已失效"),
INVALID_TOKEN(401,"token无效或已过期"),
PROGRAM_ERROR(500,"系统繁忙,请稍后再试"),
PASSWOR_ERROR(10001,"密码不正确"),
USERNAME_ALREADY_REGISTER(10003,"该用户名已注册"),

18
im-platform/src/main/java/com/bx/implatform/interceptor/AuthInterceptor.java

@ -1,14 +1,15 @@
package com.bx.implatform.interceptor;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.bx.implatform.contant.Constant;
import com.bx.implatform.config.JwtProperties;
import com.bx.implatform.enums.ResultCode;
import com.bx.implatform.exception.GlobalException;
import com.bx.implatform.session.UserSession;
import com.bx.implatform.util.JwtUtil;
import com.bx.imcommon.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
@ -18,6 +19,8 @@ import javax.servlet.http.HttpServletResponse;
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
@Autowired
private JwtProperties jwtProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
@ -27,15 +30,12 @@ public class AuthInterceptor implements HandlerInterceptor {
}
//从 http 请求头中取出 token
String token = request.getHeader("accessToken");
if (token == null) {
if (StrUtil.isEmpty(token)) {
log.error("未登陆,url:{}",request.getRequestURI());
throw new GlobalException(ResultCode.NO_LOGIN);
}
try{
//验证 token
JwtUtil.checkSign(token, Constant.ACCESS_TOKEN_SECRET);
}catch (
JWTVerificationException e) {
//验证 token
if(!JwtUtil.checkSign(token, jwtProperties.getAccessTokenSecret())){
log.error("token已失效,url:{}",request.getRequestURI());
throw new GlobalException(ResultCode.INVALID_TOKEN);
}

2
im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java

@ -98,7 +98,7 @@ public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, Gro
if(msg == null){
throw new GlobalException(ResultCode.PROGRAM_ERROR,"消息不存在");
}
if(msg.getSendId() != userId){
if(!msg.getSendId().equals(userId)){
throw new GlobalException(ResultCode.PROGRAM_ERROR,"这条消息不是由您发送,无法撤回");
}
if(System.currentTimeMillis() - msg.getSendTime().getTime() > Constant.ALLOW_RECALL_SECOND * 1000){

7
im-platform/src/main/java/com/bx/implatform/service/impl/PrivateMessageServiceImpl.java

@ -74,7 +74,7 @@ public class PrivateMessageServiceImpl extends ServiceImpl<PrivateMessageMapper,
if (msg == null) {
throw new GlobalException(ResultCode.PROGRAM_ERROR, "消息不存在");
}
if (msg.getSendId() != userId) {
if (!msg.getSendId().equals(userId)) {
throw new GlobalException(ResultCode.PROGRAM_ERROR, "这条消息不是由您发送,无法撤回");
}
if (System.currentTimeMillis() - msg.getSendTime().getTime() > Constant.ALLOW_RECALL_SECOND * 1000) {
@ -122,7 +122,6 @@ public class PrivateMessageServiceImpl extends ServiceImpl<PrivateMessageMapper,
PrivateMessageInfo info = BeanUtils.copyProperties(m, PrivateMessageInfo.class);
return info;
}).collect(Collectors.toList());
log.info("拉取聊天记录,用户id:{},好友id:{},数量:{}", userId, friendId, messageInfos.size());
return messageInfos;
}
@ -136,9 +135,7 @@ public class PrivateMessageServiceImpl extends ServiceImpl<PrivateMessageMapper,
public void pullUnreadMessage() {
// 获取当前连接的channelId
Long userId = SessionContext.getSession().getId();
String key = RedisKey.IM_USER_SERVER_ID + userId;
Integer serverId = (Integer) redisTemplate.opsForValue().get(key);
if (serverId == null) {
if (!imClient.isOnline(userId)) {
throw new GlobalException(ResultCode.PROGRAM_ERROR, "用户未建立连接");
}
// 获取当前用户所有未读消息

58
im-platform/src/main/java/com/bx/implatform/service/impl/UserServiceImpl.java

@ -1,11 +1,11 @@
package com.bx.implatform.service.impl;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bx.imclient.IMClient;
import com.bx.imcommon.contant.RedisKey;
import com.bx.implatform.contant.Constant;
import com.bx.implatform.config.JwtProperties;
import com.bx.implatform.entity.Friend;
import com.bx.implatform.entity.GroupMember;
import com.bx.implatform.entity.User;
@ -18,7 +18,7 @@ import com.bx.implatform.service.IUserService;
import com.bx.implatform.session.SessionContext;
import com.bx.implatform.session.UserSession;
import com.bx.implatform.util.BeanUtils;
import com.bx.implatform.util.JwtUtil;
import com.bx.imcommon.util.JwtUtil;
import com.bx.implatform.dto.LoginDTO;
import com.bx.implatform.dto.RegisterDTO;
import com.bx.implatform.vo.LoginVO;
@ -34,8 +34,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import static com.bx.implatform.contant.Constant.REFRESH_TOKEN_SECRET;
@Slf4j
@Service
@ -53,6 +51,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
@Autowired
private IFriendService friendService;
@Autowired
private JwtProperties jwtProperties;
@Autowired
private IMClient imClient;
/**
* 用户登录
*
@ -72,13 +75,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
// 生成token
UserSession session = BeanUtils.copyProperties(user,UserSession.class);
String strJson = JSON.toJSONString(session);
String accessToken = JwtUtil.sign(user.getId(),strJson, Constant.ACCESS_TOKEN_EXPIRE,Constant.ACCESS_TOKEN_SECRET);
String refreshToken = JwtUtil.sign(user.getId(),strJson, Constant.REFRESH_TOKEN_EXPIRE, REFRESH_TOKEN_SECRET);
String accessToken = JwtUtil.sign(user.getId(),strJson,jwtProperties.getAccessTokenExpireIn(),jwtProperties.getAccessTokenSecret());
String refreshToken = JwtUtil.sign(user.getId(),strJson,jwtProperties.getAccessTokenExpireIn(),jwtProperties.getAccessTokenSecret());
LoginVO vo = new LoginVO();
vo.setAccessToken(accessToken);
vo.setAccessTokenExpiresIn(Constant.ACCESS_TOKEN_EXPIRE);
vo.setAccessTokenExpiresIn(jwtProperties.getAccessTokenExpireIn());
vo.setRefreshToken(refreshToken);
vo.setRefreshTokenExpiresIn(Constant.REFRESH_TOKEN_EXPIRE);
vo.setRefreshTokenExpiresIn(jwtProperties.getRefreshTokenExpireIn());
return vo;
}
@ -90,22 +93,20 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
*/
@Override
public LoginVO refreshToken(String refreshToken) {
try{
//验证 token
JwtUtil.checkSign(refreshToken, REFRESH_TOKEN_SECRET);
String strJson = JwtUtil.getInfo(refreshToken);
Long userId = JwtUtil.getUserId(refreshToken);
String accessToken = JwtUtil.sign(userId,strJson, Constant.ACCESS_TOKEN_EXPIRE,Constant.ACCESS_TOKEN_SECRET);
String newRefreshToken = JwtUtil.sign(userId,strJson, Constant.REFRESH_TOKEN_EXPIRE, REFRESH_TOKEN_SECRET);
LoginVO vo =new LoginVO();
vo.setAccessToken(accessToken);
vo.setAccessTokenExpiresIn(Constant.ACCESS_TOKEN_EXPIRE);
vo.setRefreshToken(newRefreshToken);
vo.setRefreshTokenExpiresIn(Constant.REFRESH_TOKEN_EXPIRE);
return vo;
}catch (JWTVerificationException e) {
throw new GlobalException("refreshToken已失效");
//验证 token
if(JwtUtil.checkSign(refreshToken, jwtProperties.getRefreshTokenSecret())){
throw new GlobalException("refreshToken无效或已过期");
}
String strJson = JwtUtil.getInfo(refreshToken);
Long userId = JwtUtil.getUserId(refreshToken);
String accessToken = JwtUtil.sign(userId,strJson,jwtProperties.getAccessTokenExpireIn(),jwtProperties.getAccessTokenSecret());
String newRefreshToken = JwtUtil.sign(userId,strJson,jwtProperties.getAccessTokenExpireIn(),jwtProperties.getAccessTokenSecret());
LoginVO vo =new LoginVO();
vo.setAccessToken(accessToken);
vo.setAccessTokenExpiresIn(jwtProperties.getAccessTokenExpireIn());
vo.setRefreshToken(newRefreshToken);
vo.setRefreshTokenExpiresIn(jwtProperties.getRefreshTokenExpireIn());
return vo;
}
/**
@ -201,7 +202,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
List<User> users = this.list(queryWrapper);
List<UserVO> vos = users.stream().map(u-> {
UserVO vo = BeanUtils.copyProperties(u,UserVO.class);
vo.setOnline(isOnline(u.getId()));
vo.setOnline(imClient.isOnline(u.getId()));
return vo;
}).collect(Collectors.toList());
return vos;
@ -219,7 +220,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
String[] idArr = userIds.split(",");
List<Long> onlineIds = new LinkedList<>();
for(String userId:idArr){
if(isOnline(Long.parseLong(userId))){
if(imClient.isOnline(Long.parseLong(userId))){
onlineIds.add(Long.parseLong(userId));
}
}
@ -227,9 +228,4 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
}
private boolean isOnline(Long userId){
String key = RedisKey.IM_USER_SERVER_ID + userId;
Integer serverId = (Integer) redisTemplate.opsForValue().get(key);
return serverId!=null && serverId>=0;
}
}

7
im-platform/src/main/resources/application.yml

@ -41,3 +41,10 @@ webrtc:
iceServers:
- urls: stun:stun.l.google.com:19302
jwt:
accessToken:
expireIn: 1800 #半个小时
secret: MIIBIjANBgkq
refreshToken:
expireIn: 604800 #7天
secret: IKDiqVmn0VFU

24
im-server/src/main/java/com/bx/imserver/netty/processor/LoginProcessor.java

@ -6,6 +6,7 @@ import com.bx.imcommon.contant.RedisKey;
import com.bx.imcommon.enums.IMCmdType;
import com.bx.imcommon.model.IMSendInfo;
import com.bx.imcommon.model.LoginInfo;
import com.bx.imcommon.util.JwtUtil;
import com.bx.imserver.netty.IMServerGroup;
import com.bx.imserver.netty.UserChannelCtxMap;
import com.bx.imserver.netty.ws.WebSocketServer;
@ -13,6 +14,7 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@ -30,26 +32,36 @@ public class LoginProcessor extends MessageProcessor<LoginInfo> {
@Autowired
RedisTemplate<String,Object> redisTemplate;
@Value("${jwt.accessToken.secret}")
private String accessTokenSecret;
@Override
synchronized public void process(ChannelHandlerContext ctx, LoginInfo loginInfo) {
log.info("用户登录,userId:{}",loginInfo.getUserId());
ChannelHandlerContext context = UserChannelCtxMap.getChannelCtx(loginInfo.getUserId());
if(context != null){
if(!JwtUtil.checkSign(loginInfo.getAccessToken(),accessTokenSecret)){
ctx.channel().close();
log.warn("用户token校验不通过,强制下线,token:{}",loginInfo.getAccessToken());
}
Long userId = JwtUtil.getUserId(loginInfo.getAccessToken());
log.info("用户登录,userId:{}",userId);
ChannelHandlerContext context = UserChannelCtxMap.getChannelCtx(userId);
if(context != null && !ctx.channel().id().equals(context.channel().id())){
// 不允许多地登录,强制下线
IMSendInfo sendInfo = new IMSendInfo();
sendInfo.setCmd(IMCmdType.FORCE_LOGUT.code());
sendInfo.setData("您已在其他地方登陆,将被强制下线");
context.channel().writeAndFlush(sendInfo);
log.info("异地登录,强制下线,userId:{}",userId);
}
// 绑定用户和channel
UserChannelCtxMap.addChannelCtx(loginInfo.getUserId(),ctx);
UserChannelCtxMap.addChannelCtx(userId,ctx);
// 设置用户id属性
AttributeKey<Long> attr = AttributeKey.valueOf("USER_ID");
ctx.channel().attr(attr).set(loginInfo.getUserId());
ctx.channel().attr(attr).set(userId);
// 心跳次数
attr = AttributeKey.valueOf("HEARTBEAt_TIMES");
ctx.channel().attr(attr).set(0L);
// 在redis上记录每个user的channelId,15秒没有心跳,则自动过期
String key = RedisKey.IM_USER_SERVER_ID+loginInfo.getUserId();
String key = RedisKey.IM_USER_SERVER_ID+userId;
redisTemplate.opsForValue().set(key, IMServerGroup.serverId, Constant.ONLINE_TIMEOUT_SECOND, TimeUnit.SECONDS);
// 响应ws
IMSendInfo sendInfo = new IMSendInfo();

6
im-server/src/main/resources/application.yml

@ -13,4 +13,8 @@ websocket:
tcpsocket:
enable: false # 暂时不开启
port: 8879
port: 8879
jwt:
accessToken:
secret: MIIBIjANBgkq # 跟im-platfrom的secret必须一致

25
im-ui/src/api/wssocket.js

@ -3,13 +3,15 @@ let rec; //断线重连后,延迟5秒重新创建WebSocket连接 rec用来存
let isConnect = false; //连接标识 避免重复连接
let wsurl = "";
let userId = null;
let accessToken = "";
let messageCallBack = null;
let openCallBack = null;
let hasLogin = false;
let createWebSocket = (url, id) => {
let createWebSocket = (url, id,token) => {
wsurl = url;
userId = id;
accessToken = token;
initWebSocket();
};
@ -26,13 +28,12 @@ let initWebSocket = () => {
console.log('WebSocket登录成功')
// 登录成功才算连接完成
openCallBack && openCallBack();
}
else if(sendInfo.cmd==1){
} else if (sendInfo.cmd == 1) {
// 重新开启心跳定时
heartCheck.reset();
} else {
// 其他消息转发出去
messageCallBack && messageCallBack(sendInfo.cmd,sendInfo.data)
messageCallBack && messageCallBack(sendInfo.cmd, sendInfo.data)
}
}
websock.onclose = function(e) {
@ -45,10 +46,12 @@ let initWebSocket = () => {
// 发送登录命令
let loginInfo = {
cmd: 0,
data: {userId: userId}
data: {
accessToken: accessToken
}
};
websock.send(JSON.stringify(loginInfo));
}
// 连接发生错误的回调方法
@ -83,24 +86,22 @@ var heartCheck = {
timeout: 5000, //每段时间发送一次心跳包 这里设置为20s
timeoutObj: null, //延时发送消息对象(启动心跳新建这个对象,收到消息后重置对象)
start: function() {
if(isConnect){
if (isConnect) {
console.log('发送WebSocket心跳')
let heartBeat = {
cmd: 1,
data: {
userId: userId
}
data: {}
};
websock.send(JSON.stringify(heartBeat))
}
},
reset: function(){
reset: function() {
clearTimeout(this.timeoutObj);
this.timeoutObj = setTimeout(function() {
heartCheck.start();
}, this.timeout);
}
};

7
im-ui/src/view/Home.vue

@ -81,7 +81,7 @@
this.$store.commit("setUserInfo", userInfo);
this.$store.commit("setUserState", this.$enums.USER_STATE.FREE);
this.$store.commit("initStore");
this.$wsApi.createWebSocket(process.env.VUE_APP_WS_URL, userInfo.id);
this.$wsApi.createWebSocket(process.env.VUE_APP_WS_URL, userInfo.id,sessionStorage.getItem("accessToken"));
this.$wsApi.onopen(() => {
this.pullUnreadMessage();
});
@ -92,8 +92,7 @@
setTimeout(() => {
location.href = "/";
}, 1000)
} else if (cmd == 3) {
} else if (cmd == 3) {
//
this.handlePrivateMessage(msgInfo);
} else if (cmd == 4) {
@ -191,7 +190,7 @@
},
handleExit() {
this.$wsApi.closeWebSocket();
sessionStorage.removeItem("token");
sessionStorage.removeItem("accessToken");
location.href = "/";
},
playAudioTip(){

Loading…
Cancel
Save