网站首页 > 技术文章 正文
Spring Websocket是Spring框架中的一个关键组件,专门用于实现WebSocket通信。通过 @EnableWebSocket注解,它简化了WebSocket的配置和启用过程。利用 @ServerEndpoint注解,开发者可以轻松定义WebSocket端点,处理来自客户端的连接和消息。Spring Websocket支持全双工通信,允许服务器和客户端之间进行实时、双向的数据交换。此外,通过 @EnableWebSocketMessageBroker注解,它还能与STOMP消息代理集成,提供更高级的消息传递功能。这些注解的结合使用,为构建响应式和实时的Web应用程序提供了强大的支持。
肖哥弹架构 跟大家“弹弹” 框架注解使用,需要代码关注
欢迎 点赞,关注,评论。
关注公号Solomon肖哥弹架构获取更多精彩内容
历史热点文章
- 28个验证注解,通过业务案例让你精通Java数据校验(收藏篇)
- Java 8函数式编程全攻略:43种函数式业务代码实战案例解析(收藏版)
- 69 个Spring mvc 全部注解:真实业务使用案例说明(必须收藏)
- 24 个Spring bean 全部注解:真实业务使用案例说明(必须收藏)
- MySQL索引完全手册:真实业务图文讲解17种索引运用技巧(必须收藏)
- 一个项目代码讲清楚DO/PO/BO/AO/E/DTO/DAO/ POJO/VO
Spring Websocket架构图
这是一个高层次的架构图,用于展示Spring Websocket组件之间的基本关系。其中还会有更多的组件和配置,例如消息代理、安全配置、错误处理等
- 客户端 发起WebSocket请求到 WebSocket服务器。
- WebSocket服务器 可以是一个嵌入的服务器,如Tomcat或Netty,它处理WebSocket请求。
- ServerEndpointExporter 用于自动注册使用 @ServerEndpoint 注解的类。
- WebSocketConfigurer 允许自定义WebSocket配置,如注册额外的WebSocket处理器或拦截器。
- WebSocketHandlerRegistry 用于注册WebSocket处理器和它们的URL路径。
- @ServerEndpoint 定义了WebSocket服务器端点,它是客户端连接的入口点。
- WebSocketHandler 是一个接口,用于处理WebSocket生命周期事件。
- TextWebSocketHandler 和 BinaryWebSocketHandler 分别用于处理文本和二进制消息。
- @OnOpen, @OnMessage, @OnClose, @OnError 用于标记处理WebSocket连接的不同阶段的方法。
1. 配置和启用注解
@EnableWebSocket
- 注解作用介绍
@EnableWebSocket 注解用于Spring配置类上,启用基于 @ServerEndpoint的简单WebSocket支持。
- 注解属性介绍
无特定属性。
- 注解业务案例
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@EnableWebSocketMessageBroker
- 注解作用介绍
@EnableWebSocketMessageBroker 注解用于Spring配置类上,启用STOMP协议支持和消息代理功能。
- 注解属性介绍
无特定属性。
- 注解业务案例
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
}
}
2. 定义WebSocket端点
@ServerEndpoint
- 注解作用介绍
@ServerEndpoint 注解用于类上,定义一个WebSocket服务器端点,指定客户端连接的URL路径。
- 注解属性介绍value: 指定WebSocket端点的URL路径。configurator: 指定自定义的 ServerEndpointConfigurator。
- 注解业务案例
@ServerEndpoint(value = "/ws/notifications", configurator = MyConfigurator.class)
public class NotificationEndpoint {
@OnOpen
public void onOpen(Session session) {
// 处理新连接
}
@OnMessage
public void onMessage(Session session, String message) {
// 处理接收到的消息
}
@OnClose
public void onClose(Session session) {
// 处理连接关闭
}
@OnError
public void onError(Session session, Throwable error) {
// 处理连接中的错误
}
}
public class MyConfigurator implements ServerEndpointConfigurator {
// 自定义配置
}
3. 处理WebSocket生命周期事件
@OnOpen
- 注解作用介绍
@OnOpen 注解用于方法上,当WebSocket连接打开时触发。
- 注解属性介绍
无特定属性。
- 注解业务案例
public class NotificationEndpoint {
@OnOpen
public void onOpen(Session session) {
// 可以记录日志、初始化资源或发送欢迎消息
}
}
@OnClose
- 注解作用介绍
@OnClose 注解用于方法上,当WebSocket连接关闭时触发。
- 注解属性介绍
无特定属性。
- 注解业务案例
public class NotificationEndpoint {
@OnClose
public void onClose(Session session) {
// 可以记录日志、清理资源
}
}
@OnError
- 注解作用介绍
@OnError 注解用于方法上,当WebSocket连接发生错误时触发。
- 注解属性介绍
无特定属性。
- 注解业务案例
public class NotificationEndpoint {
@OnError
public void onError(Session session, Throwable error) {
// 可以记录错误日志、执行错误恢复操作
}
}
4. 接收和发送消息
@OnMessage
- 注解作用介绍 @OnMessage 注解用于方法上,当服务器接收到客户端发送的WebSocket消息时触发。
- 注解属性介绍String: 方法参数可以直接接收文本消息。byte[]: 方法参数可以接收二进制消息。Object: 方法参数可以接收反序列化后的自定义对象消息。
- 注解业务案例
public class NotificationEndpoint {
@OnMessage
public void onMessage(Session session, String message) {
// 处理接收到的文本消息
}
@OnMessage
public void onMessage(Session session, byte[] data) {
// 处理接收到的二进制消息
}
// 假设有一个自定义的消息类
@OnMessage
public void onMessage(Session session, MyCustomMessage message) {
// 处理接收到的自定义对象消息
}
}
5、综合性的应用案例
1. Spring Boot启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ChatApplication {
public static void main(String[] args) {
SpringApplication.run(ChatApplication.class, args);
}
}
2. WebSocket配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.*;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatEndpoint(), "/chat")
.setAllowedOrigins("*")
.withSockJS();
}
@Bean
public ChatEndpoint chatEndpoint() {
return new ChatEndpoint();
}
}
3. WebSocket服务器端点
import org.springframework.web.socket.*;
import org.springframework.stereotype.Component;
@Component
@ServerEndpoint("/chat")
public class ChatEndpoint {
private final ChatService chatService;
@Autowired
public ChatEndpoint(ChatService chatService) {
this.chatService = chatService;
}
@OnOpen
public void onOpen(Session session) {
chatService.addSession(session);
}
@OnClose
public void onClose(Session session) {
chatService.removeSession(session);
}
@OnError
public void onError(Session session, Throwable error) {
chatService.removeSession(session);
}
@OnMessage
public void onMessage(Session session, String message) {
chatService.broadcast(message);
}
}
4. 聊天业务逻辑服务
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class ChatService {
private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
public void addSession(WebSocketSession session) {
sessions.put(session.getId(), session);
}
public void removeSession(WebSocketSession session) {
sessions.remove(session.getId());
}
public void broadcast(String message) {
sessions.values().forEach(session -> {
try {
session.sendMessage(new TextMessage(message));
} catch (IOException e) {
// Handle exception
}
});
}
}
5. 前端页面JavaScript代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat App</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" onsubmit="return false;">
<input type="text" id="message" autocomplete="off">
<button type="submit" onclick="sendMessage()">Send</button>
</form>
<script type="text/javascript">
const socket = new WebSocket("ws://localhost:8080/chat");
const messages = document.getElementById('messages');
const form = document.getElementById('form');
const messageInput = document.getElementById('message');
form.onsubmit = () => sendMessage();
socket.onmessage = function(event) {
const message = document.createElement('li');
message.textContent = event.data;
messages.appendChild(message);
};
function sendMessage() {
const message = messageInput.value;
if (message) {
socket.send(message);
messageInput.value = '';
}
}
</script>
</body>
</html>
- 启动Spring Boot应用后, ChatApplication 类会初始化整个应用。
- WebSocketConfig 类通过 @EnableWebSocket 启用WebSocket支持,并注册 ChatEndpoint 端点。
- ChatEndpoint 类使用 @ServerEndpoint 注解定义WebSocket端点,并处理客户端连接、消息广播和异常。
- ChatService 类管理WebSocket会话,并提供广播消息的方法。
- 前端页面提供一个简单的聊天界面,用户可以输入消息并发送。消息通过WebSocket发送到服务器,服务器再将消息广播给所有连接的客户端。
猜你喜欢
- 2025-05-16 放弃 Websocket 使用 SSE 才发现这些功能两三行代码就搞定了
- 2025-05-16 我与spring webSocket不得不说的事
- 2025-05-16 从零搭建体育比分网站完整步骤
- 2025-05-16 「项目实战」.待办事项之WebSocket Web客户端(一)
- 2025-05-16 springboot 2整合websocket推送消息、数据流、解析pdf图片并压缩
- 2025-05-16 Springboot 整合 Websocket 轻松实现IM及时通讯
- 2025-05-16 现在页面实时聊天都使用Websocket技术实现吗?
- 2025-05-16 Trae验证websocket版本功能
- 2025-05-16 Spring Boot3 竟能如此轻松整合 WebSocket 技术,你还不知道?
- 2025-05-16 Springboot下的WebSocket开发
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端react (48)
- 前端md5加密 (49)
- 前端路由 (55)
- 前端数组 (65)
- 前端定时器 (47)
- 前端接口 (46)
- Oracle RAC (73)
- oracle恢复 (76)
- oracle 删除表 (48)
- oracle 用户名 (74)
- oracle 工具 (55)
- oracle 内存 (50)
- oracle 导出表 (57)
- oracle约束 (46)
- oracle 中文 (51)
- oracle链接 (47)
- oracle的函数 (57)
- mac oracle (47)
- 前端调试 (52)
- 前端登录页面 (48)
本文暂时没有评论,来添加一个吧(●'◡'●)