springboot +websocket客户端服务端
时间: 2025-06-08 09:42:35 浏览: 14
### 实现Spring Boot WebSocket客户端和服务端
#### 服务端配置
为了设置WebSocket服务器,在`application.properties`文件中定义必要的路径和传输方式:
```properties
spring.rsocket.server.mapping-path=/rsocket
spring.rsocket.server.transport=websocket
```
当这些属性匹配时,RSocket服务器将会被插入到Web服务器中[^1]。
创建一个简单的WebSocket控制器类用于处理传入的消息请求。下面是一个例子展示如何接收消息并广播给所有连接的客户:
```java
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
@Controller
public class WebSocketController {
private final SimpMessagingTemplate messagingTemplate;
public WebSocketController(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
@MessageMapping("/chat.sendMessage")
public void sendMessage(@Payload ChatMessage chatMessage) throws Exception {
Thread.sleep(1000); // simulated delay
messagingTemplate.convertAndSend("/topic/messages", chatMessage);
}
}
```
#### 客户端配置
对于客户端部分, 使用 `WebClient` 来发送HTTP请求。需要注意的是,默认情况下如果在同一应用里同时使用了Spring MVC和Spring WebFlux,则会优先选用前者;可以显式指定使用的类型来改变这一行为[^2]。
构建基于Java的应用程序入口点如下所示,这里展示了怎样通过编程的方式启动应用程序,并且可以选择关闭Banner显示以及指明源码位置[^3]:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.reactive.function.client.WebClient;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
WebClient webClient = WebClient.create("ws://localhost:8080/rsocket");
// Example of sending a message using the WebClient.
String response = webClient.post()
.uri("/chat.sendMessage")
.bodyValue(new ChatMessage())
.retrieve()
.bodyToMono(String.class)
.block();
System.out.println(response);
}
// Inner class representing a simple DTO for messages sent over WS.
record ChatMessage(String content){}
}
```
请注意上述代码片段中的URL (`ws://localhost:8080/rsocket`) 应该指向实际部署的服务地址。
阅读全文
相关推荐


















