spring boot集成websocket

引入依赖

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

配置类

  • 基本配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebsocketConfig {

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

}
  • 获取HttpSession对象配置类
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;

public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        // 获取HttpSession对象
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        // 将HttpSession对象保存起来
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);

    }
}

@ServerEndpoint(value = “/chat”,configurator = GetHttpSessionConfig.class)
要在@ServerEndpoint注解的属性中添加该类对象

代码

import com.example.mybatisplusdemo.config.GetHttpSessionConfig;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

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

@Component
@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfig.class)
public class RobotWebsocket {

    public static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();

    private HttpSession httpSession;

    private String user;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        user = (String) httpSession.getAttribute("user"); // 与登录成功时保存的key一致
        onlineUsers.put(user,session);
        // 广播消息
        broadcastAllUser(user + "上线了");

    }

    public Set getFriends(){
        return onlineUsers.keySet();
    }

    private void broadcastAllUser(String message) {
        try {
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            for (Map.Entry<String, Session> entry : entries) {
                Session session = entry.getValue();
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message){
        broadcastAllUser(user + " :" + message);
    }
    @OnClose
    public void onClose(Session session){
        onlineUsers.remove(user); // 剔除用户
        broadcastAllUser(user + "下线了");
    }

}
  • 50
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值