springboot 前端websocket
时间: 2025-01-03 20:39:15 浏览: 7
### Spring Boot 整合前端 WebSocket 实现双向通信
#### 后端配置
为了使Spring Boot应用程序支持WebSocket,在`pom.xml`文件中添加依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
创建一个配置类来启用WebSocket并注册端点[^1]。
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
```
定义处理程序逻辑,用于接收来自客户端的消息并向其发送响应。这里展示了一个简单的处理器实现方式[^2]。
```java
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println("Received Message from " + session.getId() + ": " + message.getPayload());
// Echo back the received message to client.
session.sendMessage(new TextMessage("Echo: " + message.getPayload()));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
System.out.println("Client disconnected.");
}
}
```
#### 前端页面
HTML部分设置输入框以及显示区域以便于测试连接状态和收发消息的功能。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Test Page</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script type="text/javascript">
var ws;
function connect() {
var socket = new SockJS('/ws');
ws = Stomp.over(socket);
ws.connect({}, function (frame) {
console.log('Connected: ' + frame);
ws.subscribe('/topic/messages', function (message) {
showMessage(JSON.parse(message.body).content);
});
});
}
function disconnect() {
if (ws != null) {
ws.disconnect();
}
console.log("Disconnected");
}
function sendMessage() {
var inputField = document.getElementById('inputMessage').value;
ws.send("/app/hello", {}, JSON.stringify({'name': inputField}));
}
function showMessage(message) {
var messagesListElement = document.getElementById('messages');
var liElement = document.createElement('li');
liElement.textContent = message;
messagesListElement.appendChild(liElement);
}
</script>
</head>
<body onload="connect();">
<h2>WebSocket Example</h2>
<ul id="messages"></ul>
<input type="text" id="inputMessage"/>
<button onclick="sendMessage()">Send</button>
<button onclick="disconnect()">Disconnect</button>
</body>
</html>
```
上述代码展示了如何通过SockJS库建立与服务器之间的WebSocket连接,并订阅特定的主题以监听广播消息;同时也包含了基本的操作按钮用来触发事件,比如断开链接或者发送自定义的信息给服务端。
阅读全文