diff --git a/im-client/src/main/java/com/bx/imclient/IMClient.java b/im-client/src/main/java/com/bx/imclient/IMClient.java
index 68b6b74..05a238d 100644
--- a/im-client/src/main/java/com/bx/imclient/IMClient.java
+++ b/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发送到客户端
diff --git a/im-client/src/main/java/com/bx/imclient/sender/IMSender.java b/im-client/src/main/java/com/bx/imclient/sender/IMSender.java
index 460dfa7..b4ce5c3 100644
--- a/im-client/src/main/java/com/bx/imclient/sender/IMSender.java
+++ b/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);
+ }
}
diff --git a/im-commom/pom.xml b/im-commom/pom.xml
index f998bcf..d89f74e 100644
--- a/im-commom/pom.xml
+++ b/im-commom/pom.xml
@@ -53,5 +53,11 @@
org.springframework
spring-context
+
+
+ com.auth0
+ java-jwt
+ 3.11.0
+
\ No newline at end of file
diff --git a/im-commom/src/main/java/com/bx/imcommon/contant/Constant.java b/im-commom/src/main/java/com/bx/imcommon/contant/Constant.java
index 11c1e5d..4284a5d 100644
--- a/im-commom/src/main/java/com/bx/imcommon/contant/Constant.java
+++ b/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;
+
+
+
}
diff --git a/im-commom/src/main/java/com/bx/imcommon/model/HeartbeatInfo.java b/im-commom/src/main/java/com/bx/imcommon/model/HeartbeatInfo.java
index e47bfc5..d05f305 100644
--- a/im-commom/src/main/java/com/bx/imcommon/model/HeartbeatInfo.java
+++ b/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;
}
diff --git a/im-commom/src/main/java/com/bx/imcommon/model/LoginInfo.java b/im-commom/src/main/java/com/bx/imcommon/model/LoginInfo.java
index b4eb451..f4a365f 100644
--- a/im-commom/src/main/java/com/bx/imcommon/model/LoginInfo.java
+++ b/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;
}
diff --git a/im-platform/src/main/java/com/bx/implatform/util/JwtUtil.java b/im-commom/src/main/java/com/bx/imcommon/util/JwtUtil.java
similarity index 85%
rename from im-platform/src/main/java/com/bx/implatform/util/JwtUtil.java
rename to im-commom/src/main/java/com/bx/imcommon/util/JwtUtil.java
index 33f29b3..72f6b43 100644
--- a/im-platform/src/main/java/com/bx/implatform/util/JwtUtil.java
+++ b/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;
+ }
}
}
diff --git a/im-platform/pom.xml b/im-platform/pom.xml
index c6c3dc5..33c9446 100644
--- a/im-platform/pom.xml
+++ b/im-platform/pom.xml
@@ -106,12 +106,7 @@
mybatis-plus-generator
3.3.2
-
-
- com.auth0
- java-jwt
- 3.11.0
-
+
diff --git a/im-platform/src/main/java/com/bx/implatform/config/JwtProperties.java b/im-platform/src/main/java/com/bx/implatform/config/JwtProperties.java
new file mode 100644
index 0000000..5000559
--- /dev/null
+++ b/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;
+}
diff --git a/im-platform/src/main/java/com/bx/implatform/config/MinIoClientConfig.java b/im-platform/src/main/java/com/bx/implatform/config/MinIoClientConfig.java
index 43503af..8144a56 100644
--- a/im-platform/src/main/java/com/bx/implatform/config/MinIoClientConfig.java
+++ b/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}")
diff --git a/im-platform/src/main/java/com/bx/implatform/contant/Constant.java b/im-platform/src/main/java/com/bx/implatform/contant/Constant.java
index 4aedad3..0f764c3 100644
--- a/im-platform/src/main/java/com/bx/implatform/contant/Constant.java
+++ b/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";
}
diff --git a/im-platform/src/main/java/com/bx/implatform/enums/ResultCode.java b/im-platform/src/main/java/com/bx/implatform/enums/ResultCode.java
index dc5cb40..4af3527 100644
--- a/im-platform/src/main/java/com/bx/implatform/enums/ResultCode.java
+++ b/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,"该用户名已注册"),
diff --git a/im-platform/src/main/java/com/bx/implatform/interceptor/AuthInterceptor.java b/im-platform/src/main/java/com/bx/implatform/interceptor/AuthInterceptor.java
index 064fc22..c11e7e3 100644
--- a/im-platform/src/main/java/com/bx/implatform/interceptor/AuthInterceptor.java
+++ b/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);
}
diff --git a/im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java b/im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java
index d24c9df..c358e61 100644
--- a/im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java
+++ b/im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java
@@ -98,7 +98,7 @@ public class GroupMessageServiceImpl extends ServiceImpl Constant.ALLOW_RECALL_SECOND * 1000){
diff --git a/im-platform/src/main/java/com/bx/implatform/service/impl/PrivateMessageServiceImpl.java b/im-platform/src/main/java/com/bx/implatform/service/impl/PrivateMessageServiceImpl.java
index 3e5ba22..83444e6 100644
--- a/im-platform/src/main/java/com/bx/implatform/service/impl/PrivateMessageServiceImpl.java
+++ b/im-platform/src/main/java/com/bx/implatform/service/impl/PrivateMessageServiceImpl.java
@@ -74,7 +74,7 @@ public class PrivateMessageServiceImpl extends ServiceImpl Constant.ALLOW_RECALL_SECOND * 1000) {
@@ -122,7 +122,6 @@ public class PrivateMessageServiceImpl extends ServiceImpl implements IU
@Autowired
private IFriendService friendService;
+ @Autowired
+ private JwtProperties jwtProperties;
+
+ @Autowired
+ private IMClient imClient;
/**
* 用户登录
*
@@ -72,13 +75,13 @@ public class UserServiceImpl extends ServiceImpl 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 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 implements IU
List users = this.list(queryWrapper);
List 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 implements IU
String[] idArr = userIds.split(",");
List 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 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;
- }
}
diff --git a/im-platform/src/main/resources/application.yml b/im-platform/src/main/resources/application.yml
index 8a35ae1..07678d0 100644
--- a/im-platform/src/main/resources/application.yml
+++ b/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
\ No newline at end of file
diff --git a/im-server/src/main/java/com/bx/imserver/netty/processor/LoginProcessor.java b/im-server/src/main/java/com/bx/imserver/netty/processor/LoginProcessor.java
index 2fdd903..73b3a6e 100644
--- a/im-server/src/main/java/com/bx/imserver/netty/processor/LoginProcessor.java
+++ b/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 {
@Autowired
RedisTemplate 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 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();
diff --git a/im-server/src/main/resources/application.yml b/im-server/src/main/resources/application.yml
index ee5f9e2..e3110a4 100644
--- a/im-server/src/main/resources/application.yml
+++ b/im-server/src/main/resources/application.yml
@@ -13,4 +13,8 @@ websocket:
tcpsocket:
enable: false # 暂时不开启
- port: 8879
\ No newline at end of file
+ port: 8879
+
+jwt:
+ accessToken:
+ secret: MIIBIjANBgkq # 跟im-platfrom的secret必须一致
\ No newline at end of file
diff --git a/im-ui/src/api/wssocket.js b/im-ui/src/api/wssocket.js
index f860a9a..eb3b715 100644
--- a/im-ui/src/api/wssocket.js
+++ b/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);
-
+
}
};
diff --git a/im-ui/src/view/Home.vue b/im-ui/src/view/Home.vue
index 06359c1..3b071a1 100644
--- a/im-ui/src/view/Home.vue
+++ b/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(){