springboot整合netty实现websocket消息推送,请给出以下代码:1.前端页面代码。2.前端创建、断开websocket链接以及保持心跳代码3后端Maven配置4.后端websocket实现逻辑
时间: 2023-04-04 09:05:03 浏览: 283
1. 前端页面代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Demo</title>
</head>
<body>
<h1>WebSocket Demo</h1>
<div id="message"></div>
<form>
<input type="text" id="input">
<button type="button" onclick="send()">Send</button>
</form>
<script>
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function(event) {
console.log("WebSocket connected");
};
socket.onmessage = function(event) {
var message = event.data;
console.log("Received message: " + message);
document.getElementById("message").innerHTML += "<p>" + message + "</p>";
};
socket.onclose = function(event) {
console.log("WebSocket disconnected");
};
function send() {
var message = document.getElementById("input").value;
socket.send(message);
console.log("Sent message: " + message);
}
</script>
</body>
</html>
```
2. 前端创建、断开websocket链接以及保持心跳代码:
```javascript
var socket;
function connect() {
socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function(event) {
console.log("WebSocket connected");
setInterval(function() {
socket.send("ping");
}, 5000);
};
socket.onmessage = function(event) {
var message = event.data;
console.log("Received message: " + message);
};
socket.onclose = function(event) {
console.log("WebSocket disconnected");
};
}
function disconnect() {
socket.close();
}
connect();
```
3. 后端Maven配置:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.63.Final</version>
</dependency>
</dependencies>
```
4. 后端websocket实现逻辑:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
private static class WebSocketHandler extends TextWebSocketHandler {
private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
System.out.println("WebSocket connected: " + session.getId());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
System.out.println("WebSocket disconnected: " + session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
System.out.println("Received message: " + payload);
for (WebSocketSession s : sessions) {
if (s.isOpen()) {
s.sendMessage(message);
}
}
}
}
}
```
阅读全文