springboot 实现websocket 客户端多个链接祥细代码
时间: 2023-07-06 07:04:50 浏览: 139
下面是一个简单的 Spring Boot WebSocket 客户端示例,可以建立多个 WebSocket 连接:
首先,添加依赖:
```xml
<!-- WebSocket 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
然后,创建一个 `WebSocketClient` 类,用于建立 WebSocket 连接:
```java
@Component
public class WebSocketClient {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
/**
* 建立 WebSocket 连接
*
* @param url WebSocket URL
* @throws Exception
*/
public void connect(String url) throws Exception {
WebSocketHandler handler = new MyWebSocketHandler();
WebSocketSession session = new StandardWebSocketClient()
.doHandshake(handler, null, new URI(url))
.get();
logger.info("WebSocket 连接已建立:{}", url);
sessions.put(url, session);
}
/**
* 发送消息
*
* @param url WebSocket URL
* @param message 消息内容
* @throws Exception
*/
public void sendMessage(String url, String message) throws Exception {
WebSocketSession session = sessions.get(url);
if (session != null && session.isOpen()) {
session.sendMessage(new TextMessage(message));
logger.info("已发送消息:{}", message);
} else {
logger.warn("WebSocket 连接不存在或已关闭:{}", url);
}
}
/**
* 关闭连接
*
* @param url WebSocket URL
* @throws Exception
*/
public void close(String url) throws Exception {
WebSocketSession session = sessions.get(url);
if (session != null && session.isOpen()) {
session.close();
logger.info("WebSocket 连接已关闭:{}", url);
} else {
logger.warn("WebSocket 连接不存在或已关闭:{}", url);
}
sessions.remove(url);
}
/**
* WebSocket 处理器
*/
private class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.info("WebSocket 连接已建立:{}", session.getUri());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("已收到消息:{}", message.getPayload());
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
logger.error("WebSocket 连接出现异常:{}", session.getUri(), exception);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
logger.info("WebSocket 连接已关闭:{},状态码:{},原因:{}", session.getUri(), status.getCode(), status.getReason());
}
}
}
```
在 `WebSocketClient` 类中,我们通过 Map 存储多个 WebSocket 连接,使用 `connect()` 方法创建一个新的 WebSocket 连接,使用 `sendMessage()` 方法发送消息,使用 `close()` 方法关闭连接。
此外,我们还定义了一个内部类 `MyWebSocketHandler`,继承自 `TextWebSocketHandler`,用于处理 WebSocket 消息。
最后,在需要使用 WebSocket 客户端的地方,注入 `WebSocketClient` 即可:
```java
@RestController
public class MyController {
@Autowired
private WebSocketClient webSocketClient;
@GetMapping("/connect")
public void connect() throws Exception {
webSocketClient.connect("ws://localhost:8080/ws");
webSocketClient.connect("ws://localhost:8081/ws");
}
@GetMapping("/send")
public void send() throws Exception {
webSocketClient.sendMessage("ws://localhost:8080/ws", "Hello, WebSocket 1!");
webSocketClient.sendMessage("ws://localhost:8081/ws", "Hello, WebSocket 2!");
}
@GetMapping("/close")
public void close() throws Exception {
webSocketClient.close("ws://localhost:8080/ws");
webSocketClient.close("ws://localhost:8081/ws");
}
}
```
在上面的代码中,我们调用 `WebSocketClient` 的 `connect()` 方法建立两个 WebSocket 连接,调用 `sendMessage()` 方法发送消息,调用 `close()` 方法关闭连接。
阅读全文