springboot整合netty实现websocket消息推送,请给出前端页面及连接断开代码和后端处理代码
时间: 2023-04-04 19:04:56 浏览: 297
SpringBoot+WebSocket+Netty实现消息推送的示例代码
5星 · 资源好评率100%
感谢您的提问。以下是前端页面及连接断开代码和后端处理代码:
前端页面代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<div id="message"></div>
<script>
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onmessage = function(event) {
var message = event.data;
document.getElementById("message").innerHTML += "<p>" + message + "</p>";
};
socket.onclose = function(event) {
document.getElementById("message").innerHTML += "<p>连接已断开</p>";
};
</script>
</body>
</html>
```
连接断开代码:
```
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
String channelId = channel.id().asLongText();
log.info("连接已断开,channelId: {}", channelId);
channelGroup.remove(channel);
}
```
后端处理代码:
```
@Component
@ChannelHandler.Sharable
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static final Logger log = LoggerFactory.getLogger(WebSocketServerHandler.class);
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
String channelId = channel.id().asLongText();
log.info("新连接加入,channelId: {}", channelId);
channelGroup.add(channel);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
String message = msg.text();
log.info("接收到消息: {}", message);
channelGroup.writeAndFlush(new TextWebSocketFrame("服务器收到消息: " + message));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("发生异常: ", cause);
ctx.close();
}
}
```
希望能够帮助到您。
阅读全文