POM文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置文件Config
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
SocketService
@Component
@ServerEndpoint("/websocket/{type}/{token}")
public class SokcetService {
private static SocketService socketService;
private static int onlineCount = 0;
private static ConcurrentHashMap<String, SocketService> socketMap = new ConcurrentHashMap<>();
private Session session;
private String uuid = "";
@Autowired
private TestService testService;
@Autowired
private TokenService tokenService;
@PostConstruct
private void init() {
socketService = this;
socketService.testService = this.testService;
socketService.tokenService = this.tokenService;
}
@OnOpen
public void onOpen(Session session, @PathParam("type") String type, @PathParam("token") String token) {
this.session = session;
Long userId = socketService.tokenService.getUserId(token)
this.uuid = String.format("%s%s%s", type, userId, IdUtil.randomUUID());
if (!socketMap.containsKey(this.uuid)) {
addOnlineCount();
}
socketMap.put(this.uuid, this);
}
@OnMessage
public void onMessage(@NotNull String message, Session session) {
}
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
@OnClose
public void onClose() {
if (socketMap.containsKey(uuid)) {
socketMap.remove(uuid);
subOnlineCount();
}
log.debug("WebSocket---连接关闭, 用户id:{} 当前在线人数为:{}", uuid, getOnlineCount());
}
@OnError
public void onError(Throwable error) {
}
private static synchronized int getOnlineCount() {
return onlineCount;
}
private static synchronized void addOnlineCount() {
socketService.onlineCount++;
}
private static synchronized void subOnlineCount() {
socketService.onlineCount--;
}
}