SpringBoot集成WebSocket

@Configuration
public class WebSocketConfig implements ServletContextInitializer {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addListener(WebAppRootListener.class);
        servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize", "52428800");
        servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize", "52428800");
    }
}
import com.tizo.biz.base.utils.AssertLog;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/notice/{userId}")
public class WebSocketServer {

    /**
     * ConcurrentHashMap包的线程安全Map,用来存放每个客户端对应的Session对象。
     */
    private static final ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).close();
            webSocketMap.remove(userId);
        }
        webSocketMap.put(userId, session);
        AssertLog.info(session.getRequestURI().getPath() + ",用户连接:" + userId + ",当前在线人数为:" + webSocketMap.size());
        try {
            sendMessage("连接成功", session);
        } catch (IOException e) {
            AssertLog.error("用户:" + userId + ",网络异常!!!!!!" + e.getMessage());
            session.close();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId, Session session) {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
        }
        AssertLog.info(session.getRequestURI().getPath() + ",用户退出:" + userId + ",当前在线人数为:" + webSocketMap.size());
        try {
            session.close();
        } catch (IOException e) {
            AssertLog.error("关闭连接异常:" + e.getMessage());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(@PathParam("userId") String userId, String message, Session session) {
        AssertLog.info(session.getRequestURI().getPath() + ",接收用户ID:" + userId + ",接收报文:" + message);
    }

    /**
     * 异常
     */
    @OnError
    public void onError(@PathParam("userId") String userId, Session session, Throwable error) {
        AssertLog.error(session.getRequestURI().getPath() + ",用户错误:" + userId + ",原因:" + error.getMessage());
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message, Session session) throws IOException {
        session.getAsyncRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendMessage(String userId, String message) {
        AssertLog.info("发送消息给:" + userId + ",发送报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).getAsyncRemote().sendText(message);
        } else {
            AssertLog.error("用户" + userId + ",不在线!");
        }
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NuoleAQ

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值