Files
gxtyzx-java/modules/common/core/socketio/config/SocketIOConfig.java
T
2024-08-13 17:51:18 +08:00

83 lines
2.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.gxwebsoft.common.core.socketio.config;
import com.corundumstudio.socketio.SocketIOServer;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.security.JwtSubject;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.socketio.cache.ClientCache;
import com.gxwebsoft.common.core.socketio.handler.SocketIOHandler;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.io.InputStream;
/**
* socket服务配置
* @author machenike
*/
@Configuration
public class SocketIOConfig implements InitializingBean {
private final static Logger logger = LoggerFactory.getLogger(SocketIOConfig.class);
@Value("${socketio.host}")
private String host;
@Value("${socketio.port}")
private Integer port;
@Resource
private SocketIOHandler socketIOHandler;
@Resource
private UserService userService;
@Resource
private ConfigProperties configProperties;
@Override
public void afterPropertiesSet() throws Exception {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
//设置host
config.setHostname(host);
//设置端口
config.setPort(port);
config.setBossThreads(1);
config.setAuthorizationListener(handshakeData -> {
String userId =handshakeData.getSingleUrlParam("userId");
String token = handshakeData.getSingleUrlParam("token");
logger.info("身份验证 token:{}", token);
if(!StringUtils.hasText(token) || !StringUtils.hasText(userId)){
return false;
}
// 身份验证
Claims claims = JwtUtil.parseToken(token, configProperties.getTokenKey());
JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
User user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());
if (user == null || !user.getUserId().equals(Integer.valueOf(userId))) {
return false;
}
return true;
});
InputStream resourceAsStream = this.getClass().getResourceAsStream("/jks/love.jks"); // 读取证书文件流
config.setKeyStore(resourceAsStream); // 设置证书文件
config.setKeyStorePassword("123456"); // 设置证书密码
// 启动socket服务
// SocketIOServer server = new SocketIOServer(config);
// server.addListeners(socketIOHandler);
// server.start();
// ClientCache.setSocketIOServer(server);
// logger.debug("Netty SocketIO启动:{}:{}",host,port);
}
}