springboot使用websocket

文章目录

一、概述

1、简介

简介略,附上官方文档,spring5和spring6的官方文档内容大致是一样的:
https://docs.spring.io/spring-framework/docs/5.2.25.RELEASE/spring-framework-reference/web.html#websocket
https://docs.spring.io/spring-framework/reference/6.1/web/websocket.html

二、 使用

1、引包

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、配置处理器

创建WebSocket服务器可以实现WebSocketHandler或者,更有可能的是,扩展TextWebSocketHandler或者BinaryWebSocketHandler。以下示例使用TextWebSocketHandler

java 复制代码
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.CopyOnWriteArrayList;

public class MyHandler extends TextWebSocketHandler {

    // 可以定义一个存储所有session的容器
    private final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 建立请求
        sessions.add(session);
        System.out.println("Connection established: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 收到消息
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);
        // 发送回复消息
        for (WebSocketSession s : sessions) {
            s.sendMessage(new TextMessage("Server received: " + payload));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 关闭链接
        sessions.remove(session);
        System.out.println("Connection closed: " + session.getId());
    }

}
java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

	/**
	 * 将前面的WebSocket处理程序映射到特定的URL
	 */
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(myHandler(), "/myHandler")
				//.addInterceptors(new HttpSessionHandshakeInterceptor()) // 可以拦截session属性
				.setAllowedOrigins("*"); // 跨域
		;
	}

	@Bean
	public WebSocketHandler myHandler() {
		return new MyHandler();
	}

}

3、前端测试

测试地址:https://tool.gitapp.cn/websocket/

连接ws://127.0.0.1:8080/myHandler,发送消息进行测试一下。

使用起来非常的方便

相关推荐
爱吃牛肉的大老虎13 分钟前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
石榴19 分钟前
NestJS 的请求到底经过了什么:装饰器、守卫、拦截器、管道与中间件如何配合
后端
Gopher_HBo27 分钟前
moby-client客户端
后端
杨运交1 小时前
[055][调度模块]Spring动态任务调度框架的设计与实现
java·后端·spring
卷福同学2 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端
Csvn3 小时前
📊 SQL 入门 Day 11:CASE 表达式:SQL 里的 if-else 魔法
后端·sql
QQ_21696290963 小时前
Spring Boot 养老院管理系统:从入住、护理到费用结算的全流程实现(源码可领)
java·spring boot·后端
万少5 小时前
DeepSeek-V4-Flash 正式版上线了,但这 3 个坑我帮你提前踩了
前端·javascript·后端
明月_清风5 小时前
🚀 Palantir Foundry 本体论实战:当 Ontology 从"知识图谱"进化为"企业操作系统"
前端·后端
明月_清风6 小时前
从概念到代码:用 Ontology 构建你的第一个知识图谱
前端·后端