vue3+java实现websocket
时间: 2023-11-12 13:58:13 浏览: 114
要实现Vue3和Java的WebSocket通信,可以使用Vue3的WebSocket API和Java的WebSocket API。具体步骤如下:
1. 在Vue3中使用WebSocket API建立WebSocket连接:
```javascript
const socket = new WebSocket('ws://localhost:8080/ws');
socket.addEventListener('open', (event) => {
console.log('WebSocket连接已打开');
});
socket.addEventListener('message', (event) => {
console.log('收到消息:', event.data);
});
socket.addEventListener('close', (event) => {
console.log('WebSocket连接已关闭');
});
socket.addEventListener('error', (event) => {
console.error('WebSocket连接发生错误:', event);
});
```
2. 在Java中使用WebSocket API建立WebSocket连接:
```java
@ServerEndpoint("/ws")
public class WebSocketServer {
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket连接已打开");
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("收到消息:" + message);
session.getBasicRemote().sendText("收到消息:" + message);
}
@OnClose
public void onClose(Session session) {
System.out.println("WebSocket连接已关闭");
}
@OnError
public void onError(Throwable error) {
System.err.println("WebSocket连接发生错误:" + error);
}
}
```
3. 在Vue3中发送消息:
```javascript
socket.send('Hello, WebSocket!');
```
4. 在Java中发送消息:
```java
session.getBasicRemote().sendText("Hello, WebSocket!");
```
阅读全文