> For the complete documentation index, see [llms.txt](https://potoyang.gitbook.io/spring-in-action-v4/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://potoyang.gitbook.io/spring-in-action-v4/untitled-11.md).

# 第 18 章　使用 WebSocket 和 STOMP 实现消息功能

本章内容：

* 在浏览器和服务器之间发送消息
* 在 Spring MVC 控制器中处理消息
* 为目标用户发送消息

在上一章中，我们看到了如何使用 JMS 和 AMQP 在应用程序之间发送消息。异步消息是应用程序之间通用的交流方式。但是，如果某一应用是运行在 Web 浏览器中，那我们就需要一些稍微不同的技巧了。

WebSocket 协议提供了通过一个套接字实现全双工通信的功能。除了其他的功能之外，它能够实现 Web 浏览器和服务器之间的异步通信。全双工意味着服务器可以发送消息给浏览器，浏览器也可以发送消息给服务器。

Spring 4.0 为 WebSocket 通信提供了支持，包括：

* 发送和接收消息的低层级 API；
* 发送和接收消息的高级 API；
* 用来发送消息的模板；
* 支持 SockJS，用来解决浏览器端、服务器以及代理不支持 WebSocket 的问题。

在本章中，我们将会学习借助 Spring 的 WebSocket 功能实现服务器端和基于浏览器的应用之间实现异步通信。我们首先会从如何使用 Spring 的低层级 WebSocket API 开始。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://potoyang.gitbook.io/spring-in-action-v4/untitled-11.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
