springboot + websocket server receives messages & actively sends messages

1. Introduce maven configuration:

		<dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-websocket</artifactId>  
       </dependency> 

Two, config configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * WebSocket配置
 *
 * @author 
 * @version v1.0.0
 * @since 2021/5/17 16:00
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

3. Message receiving and sending server:

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket server服务
 *
 * @author 
 * @version v1.0.0
 * @since 2021/5/17 16:30
 */
@ServerEndpoint("/{userId}")
@Component
public class WebSocketServer {

    private static int onlineCount = 0;     // 统计在线人数,粗略统计,未涉及并发
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();   // session管理map
    private Session session;    // 会话session
    private String userId="";   // 当前用户

    /**
     * 初始化连接
     *
     * @param session 会话session
     * @param userId 当前用户id
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;

        // 保存各用户的会话session
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        }else{
            webSocketMap.put(userId, this);
            addOnlineCount();
        }

        try {
            sendMessage("connect success");
        } catch (IOException e) {
     
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            subOnlineCount();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    }

    /**
     * 异常处理
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     *
     * @param message 消息体
     * */
    public void sendInfo(String message) throws IOException {

        List<String> keys = new ArrayList<>(webSocketMap.keySet());
        if (CollectionUtils.isNotEmpty(keys)) {
            for (String key : keys) {
                webSocketMap.get(key).sendMessage(message);
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

Among them, the sendInfo(String message) method is the method exposed to other classes to actively send messages to the specified websocket, such as in class A through webSocketServer.sendInfo(msg); to actively send messages. In the code example, the message is sent to all users, or the message can be sent to the specified user according to actual needs

Guess you like

Origin blog.csdn.net/sxg0205/article/details/116938521