springboot+vue2代码实现WebSocket通信
时间: 2024-01-16 14:02:16 浏览: 144
好的,下面是一个简单的示例代码:
后端使用Spring Boot实现WebSocket:
1.添加依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2.创建WebSocket配置类:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
```
3.创建WebSocketHandler:
```java
public class WebSocketHandler extends TextWebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.info("建立连接:{}", session.getId());
sessions.add(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("收到消息:{}", message.getPayload());
for (WebSocketSession s : sessions) {
if (s.isOpen()) {
s.sendMessage(message);
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
logger.info("关闭连接:{},状态:{}", session.getId(), status);
sessions.remove(session);
}
}
```
前端使用Vue2实现WebSocket:
1.安装依赖:
```bash
npm install --save vue-native-websocket
```
2.在Vue实例中注册WebSocket:
```vue
<template>
<div>
<input v-model="message" @keyup.enter="sendMessage" placeholder="请输入消息"/>
<ul>
<li v-for="(msg, index) in messages" :key="index">{{msg}}</li>
</ul>
</div>
</template>
<script>
import VueNativeSock from 'vue-native-websocket';
export default {
data() {
return {
message: '',
messages: []
};
},
methods: {
sendMessage() {
this.$socket.send(this.message);
this.message = '';
}
},
created() {
this.$options.sockets.onmessage = (event) => {
this.messages.push(event.data);
};
},
sockets: {
connect: () => {
console.log('WebSocket连接成功');
},
disconnect: () => {
console.log('WebSocket断开连接');
}
}
};
</script>
```
以上就是一个简单的Spring Boot和Vue2实现WebSocket通信的示例代码。
阅读全文