提供一个springboot项目客户端通过socket连接服务端并且互相发送信息的方法,要求是在springboot项目里面,controller里面调用
时间: 2023-12-15 18:07:32 浏览: 69
首先,需要引入spring-boot-starter-websocket依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
然后,创建一个WebSocket配置类,用来配置WebSocket相关的类:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler(), "/my-websocket");
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
}
```
其中,MyWebSocketHandler是自定义的WebSocket处理器,处理来自客户端的消息。
下面是MyWebSocketHandler的实现:
```java
public class MyWebSocketHandler implements WebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(MyWebSocketHandler.class);
private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.info("WebSocket连接建立: " + session.getId());
sessions.add(session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
logger.info("收到消息: " + message.getPayload());
for (WebSocketSession s : sessions) {
if (s.isOpen() && !s.getId().equals(session.getId())) {
s.sendMessage(message);
}
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
logger.error("WebSocket连接异常: " + session.getId(), exception);
sessions.remove(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
logger.info("WebSocket连接关闭: " + session.getId());
sessions.remove(session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
```
这里实现了WebSocketHandler接口,并在afterConnectionEstablished方法中记录连接,handleMessage方法中处理消息,handleTransportError和afterConnectionClosed方法中移除连接。
最后,在Controller中注入WebSocketHandler,即可通过WebSocket与客户端进行交互:
```java
@RestController
public class MyController {
@Autowired
private WebSocketHandler webSocketHandler;
@GetMapping("/send-message")
public String sendMessage(@RequestParam String message) {
for (WebSocketSession session : ((MyWebSocketHandler) webSocketHandler).sessions) {
try {
session.sendMessage(new TextMessage(message));
} catch (IOException e) {
e.printStackTrace();
}
}
return "OK";
}
}
```
这里定义了一个/send-message接口,用来向所有连接的客户端发送消息。在Controller中注入WebSocketHandler,并通过sessions属性获取所有连接的WebSocketSession,然后通过sendMessage方法发送消息。
至此,一个可以通过WebSocket连接并互相发送信息的Spring Boot项目就完成了。
阅读全文