Spring Boot项目——Spring Boot配置websocket

步骤

  • 引入依赖
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 创建配置
复制代码
@Configuration
public class WebsocketConfig {

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

}
复制代码
  • 创建service
复制代码
@Component
@ServerEndpoint("/websocket/{userName}")
public class WebSocketServiceImpl {
    private Session session;

    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userName")String userName) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(userName, session);
        System.out.println(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for(WebSocketServiceImpl webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userName, String message) {
        System.out.println("【websocket消息】单点消息:"+message);
        Session session = sessionPool.get(userName);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
复制代码
    • 注意此处@ServerEndpoint注解的值要和前端通信的接口地址保持一致,否则不能连接通信。
  • Websocket Server 已经搭建完成,客户端已经可以和服务端通信了。服务端 向客户端推送消息 通过 session.getBasicRemote().sendText(message)

测试

  • 代码如下
复制代码
@RequestMapping("/websocket")
@RestController
public class WebSocketController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WebSocketServiceImpl webSocketService;

    @ResponseBody
    @GetMapping("/sendAllWebSocket")
    public String test() {
        String text="你们好!这是websocket群体发送!";
        webSocketService.sendAllMessage(text);
        return text;
    }

    @GetMapping("/sendOneWebSocket/{userName}")
    public String sendOneWebSocket(@PathVariable("userName") String userName) {
        String text=userName+" 你好! 这是websocket单人发送!";
        webSocketService.sendOneMessage(userName,text);
        return text;
    }
}
复制代码
    • 通过url测试通信结果,前端可以打印信息
posted @   话·醉月  阅读(1109)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示