springboot vue websocket项目案例
时间: 2023-07-01 17:18:38 浏览: 224
以下是一个简单的 Spring Boot + Vue.js + WebSocket 的项目案例,该项目实现了一个简单的在线聊天室:
后端部分(Spring Boot + WebSocket):
1. 创建 Spring Boot 项目,在 pom.xml 中添加 WebSocket 和 Thymeleaf 的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 创建 WebSocket 配置类:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatWebSocketHandler(), "/chat").setAllowedOrigins("*");
}
}
```
3. 创建 WebSocket 处理类:
```java
public class ChatWebSocketHandler extends TextWebSocketHandler {
private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession s : sessions) {
s.sendMessage(message);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
}
```
4. 创建一个简单的控制器,用于返回聊天室页面:
```java
@Controller
public class ChatController {
@GetMapping("/")
public String index() {
return "index";
}
}
```
5. 创建聊天室页面 index.html:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat Demo</title>
</head>
<body>
<h1>WebSocket Chat Demo</h1>
<div>
<div id="message-list"></div>
<form id="chat-form">
<input type="text" id="message-input">
<button type="submit">Send</button>
</form>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="/js/chat.js"></script>
</body>
</html>
```
6. 创建 JavaScript 文件 chat.js,用于连接 WebSocket 服务器并处理消息:
```javascript
$(function () {
var socket = new WebSocket("ws://" + location.host + "/chat");
socket.onopen = function () {
console.log("WebSocket connection established.");
};
socket.onmessage = function (event) {
var message = event.data;
$("#message-list").append($("<div>").text(message));
};
socket.onclose = function () {
console.log("WebSocket connection closed.");
};
$("#chat-form").submit(function (event) {
event.preventDefault();
var message = $("#message-input").val();
socket.send(message);
$("#message-input").val("");
});
});
```
前端部分(Vue.js):
1. 在根目录下创建一个 public/js 目录,用于存放 Vue.js 和 chat.js 文件。
2. 在 index.html 中引入 Vue.js 文件:
```html
<script src="https://cdn.bootcss.com/vue/2.6.11/vue.min.js"></script>
```
3. 创建 Vue.js 组件 ChatRoom,用于显示聊天室页面:
```html
<template>
<div>
<div id="message-list">
<div v-for="message in messages" :key="message">{{ message }}</div>
</div>
<form @submit.prevent="sendMessage">
<input v-model="messageText" type="text" id="message-input">
<button type="submit">Send</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
messages: [],
messageText: ''
}
},
mounted() {
var socket = new WebSocket("ws://" + location.host + "/chat");
socket.onmessage = event => {
var message = event.data;
this.messages.push(message);
};
},
methods: {
sendMessage() {
var socket = new WebSocket("ws://" + location.host + "/chat");
socket.send(this.messageText);
this.messageText = '';
}
}
}
</script>
```
4. 创建 main.js 文件,用于创建 Vue.js 实例并挂载到页面:
```javascript
import Vue from 'vue'
import ChatRoom from './components/ChatRoom.vue'
new Vue({
el: '#app',
components: { ChatRoom },
template: '<ChatRoom/>'
})
```
5. 修改 index.html,使用 Vue.js 组件替代原有的 HTML 代码:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat Demo</title>
</head>
<body>
<h1>WebSocket Chat Demo</h1>
<div id="app">
<chat-room></chat-room>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.11/vue.min.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
```
以上就是一个简单的 Spring Boot + Vue.js + WebSocket 的项目案例。
阅读全文