在springboot环境中实现一个websocket连接,给出详细的前端和后端代码
时间: 2024-09-30 09:07:32 浏览: 34
在Spring Boot中实现WebSocket连接涉及到Spring Websocket框架。以下是简单的前端和后端步骤:
**前端代码(JavaScript + HTML) - 使用vue.js为例**:
```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<button @click="connectSocket">连接WebSocket</button>
<pre>{{message}}</pre>
</div>
<script>
new Vue({
el: '#app',
data: {
message: ''
},
methods: {
connectSocket() {
this.socket = new WebSocket('ws://' + window.location.host + '/chat');
this.socket.onopen = () => {
console.log('WebSocket已连接');
};
this.socket.onmessage = (event) => {
this.message = event.data;
};
}
}
});
</script>
</body>
</html>
```
**后端代码(Java with Spring Boot)**:
首先,在`pom.xml`添加依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
然后创建一个WebSocket配置类,比如`WebSocketConfig.java`:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.server.standard.ServerTransportHandler;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig {
@Bean
public ServerTransportHandler transportHandler() {
return new SimpleServerTransportHandler();
}
@Bean
public StompEndpointRegistry stompEndpointRegistry() {
StompEndpointRegistry registry = new StompEndpointRegistry(this);
registry.addEndpoint("/chat");
return registry;
}
}
```
最后,创建一个处理消息发送和接收的Stomp endpoint处理器,如`ChatController.java`:
```java
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
@Controller
public class ChatController {
@MessageMapping("/chat")
public TextMessage handleMessage(String message) {
// 这里可以做一些业务处理,例如保存到数据库等
System.out.println("Received message: " + message);
return new TextMessage("You said: " + message);
}
}
```
阅读全文