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,发送消息进行测试一下。

使用起来非常的方便

相关推荐
Livingbody7 分钟前
基于【ERNIE-4.5-VL-28B-A3B】模型的图片内容分析系统
后端
你的人类朋友1 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
张先shen2 小时前
Elasticsearch RESTful API入门:基础搜索与查询DSL
大数据·spring boot·elasticsearch·搜索引擎·全文检索·restful
追逐时光者2 小时前
面试第一步,先准备一份简洁、优雅的简历模板!
后端·面试
慕木兮人可3 小时前
Docker部署MySQL镜像
spring boot·后端·mysql·docker·ecs服务器
发粪的屎壳郎3 小时前
ASP.NET Core 8 轻松配置Serilog日志
后端·asp.net·serilog
倔强青铜三4 小时前
苦练Python第4天:Python变量与数据类型入门
前端·后端·python
倔强青铜三4 小时前
苦练Python第3天:Hello, World! + input()
前端·后端·python
倔强青铜三4 小时前
苦练Python第2天:安装 Python 与设置环境
前端·后端·python
Kookoos4 小时前
ABP VNext + .NET Minimal API:极简微服务快速开发
后端·微服务·架构·.net·abp vnext