POM file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Copy the code
Config file
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(a) {
return newServerEndpointExporter(); }}Copy the code
SocketService
// @param type Service type
// @param token user information
@Component
@ServerEndpoint("/websocket/{type}/{token}")
public class SokcetService {
private static SocketService socketService;
// Number of current connections
private static int onlineCount = 0;
// Store the webSocket object corresponding to each client
private static ConcurrentHashMap<String, SocketService> socketMap = new ConcurrentHashMap<>();
// A connection session with a client through which to send data to the client
private Session session;
private String uuid = "";
// The injected business interface
@Autowired
private TestService testService;
@Autowired
private TokenService tokenService;
// Initialize the mount bean
@PostConstruct
private void init(a) {
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;
// Construct uUID - business code - need to be replaced
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);
}
// The server receives
@OnMessage
public void onMessage(@NotNull String message, Session session) {
// Business logic
}
// Server actively push
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
@OnClose
public void onClose(a) {
if (socketMap.containsKey(uuid)) {
socketMap.remove(uuid);
subOnlineCount();
}
log.debug("WebSocket-- connection closed, user ID: {} Number of current online users: {}", uuid, getOnlineCount());
}
@OnError
public void onError(Throwable error) {}// Get the number of people online
private static synchronized int getOnlineCount(a) {
return onlineCount;
}
// Add one to the number of people online
private static synchronized void addOnlineCount(a) {
socketService.onlineCount++;
}
// The number of people online is reduced by one
private static synchronized void subOnlineCount(a) { socketService.onlineCount--; }}Copy the code