websocket springboot 发送消息
时间: 2025-01-16 20:09:20 浏览: 40
### 如何在Spring Boot项目中通过WebSocket发送消息
#### 配置WebSocket支持
为了使Spring Boot应用程序能够处理WebSocket连接,需要引入必要的依赖并配置相应的组件。
在`pom.xml`文件中加入WebSocket启动器:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
接着定义一个配置类用于注册WebSocket端点导出器[^2]:
```java
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
```
#### 实现WebSocket服务端逻辑
创建一个新的Java类作为WebSocket服务器端处理器。此处理器负责接收来自客户端的消息并向其响应或广播给其他已连接的客户[^1]。
```java
@ServerEndpoint("/ws/{userId}")
@Component
public class MyWebSocketHandler {
private static final Set<MyWebSocketHandler> webSocketSet = Collections.synchronizedSet(new HashSet<>());
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) throws IOException {
System.out.println("New connection from " + userId);
webSocketSet.add(this);
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("Received message: " + message);
// Echo back the received message to all connected clients.
synchronized (webSocketSet) {
for (MyWebSocketHandler handler : webSocketSet) {
try {
handler.sendMessageToClient(message);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
}
@OnError
public void onError(Throwable error){
System.err.println(error.getMessage());
}
@OnClose
public void onClose(){
webSocketSet.remove(this);
System.out.println("Connection closed");
}
private void sendMessageToClient(String msg) throws IOException{
this.session.getBasicRemote().sendText(msg);
}
}
```
注意上述代码中的路径参数`{userId}`可以用来区分不同的会话用户;而集合`webSocketSet`则保存着当前所有的活动连接实例以便于群发消息[^4]。
当有新的客户端尝试建立连接时触发`onOpen()`方法,在这里还可以执行初始化操作比如记录用户的唯一标识符等信息。每当接收到一条新消息就会调用`onMessage()`函数来进行相应处理——在这个例子里面就是简单地把该条消息转发给了每一个在线成员。如果发生错误,则由`onError()`捕获异常堆栈跟踪日志输出到控制台方便排查问题所在之处。最后,一旦某个特定客户的断开请求到达就激活`onClose()`完成清理工作[^3]。
阅读全文
相关推荐




















