SpringBoot +WebSocket 小程序聊天(demo)

1. 依赖



	org.springframework.boot
	spring-boot-starter-websocket

2. 自动注册配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 
  
3. WebSocket服务类

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint("/wx/websocket/{userId}") //必须将参数放到该地址中传递
@Component
public class WebSocketController {


    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 用于存所有的连接服务的客户端,这个对象存储是安全的
     */
    private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();


    /**
     * 连接建立成功调用的方法
     *
     * @param session
     * @param userId    接收地址上的参数
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info("连接成功, 有新用户加入,userId={}, 当前在线人数为:{}", userId, webSocketMap.size());

        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            //加入map中
        } else {
            webSocketMap.put(userId, this);
            //加入map中
        }
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(){
        System.out.println("连接关闭");
        webSocketMap.remove(this);  //从map中删除
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message   客户端发送过来的消息
     */
    @OnMessage
    public void OnMessage(String message) {
        this.sendMessage(message);
    }


    /**
     *  服务端发送消息给客户端
     *
     * @param message
     */
    private void sendMessage(String message){
        try {

            log.info("服务端给客户端[{}]发送消息{}", message);

            // 实现服务器主动推送
            this.session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) {
        log.info(message);

        for (Map.Entry entry : webSocketMap.entrySet()) {
            try {
                entry.getValue().sendMessage(message);
            } catch (Exception e) {
                continue;
            }
        }
    }

    /**
     * 报错
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");

        error.printStackTrace();
    }


    /**
     * 自定义关闭
     *
     * @param userId
     */
    public static void close(String userId) {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
        }
    }

    /**
     * 获取在线用户信息
     *
     * @return
     */
    public static Map getOnlineUser() {
        return webSocketMap;
    }
}

你可能感兴趣的:(webSocket,spring,boot,websocket,后端)