一、html页面
这里使用了Jquery框架。定时(每5秒)向服务端发送"ping", 如果服务端返回的报文是"pong",则认为是心跳请求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket</title>
<script src="./jquery-3.4.1.js" type="text/javascript" charset="UTF-8"></script>
</head>
<script>
$(function(){
var ws = new WebSocket("ws://192.168.8.28:8889");
var heartTime;
if(window.WebSocket){
// 连接服务器
ws.onopen = function(){
// debugger 开启断点模式
var html = "<span style='color:green'>连接服务器成功</span></br>";
$("#toke").append(html);
// 连接成功后发送心跳
sendHeart();
}
// 断开服务器
ws.onclose = function(e){
clearInterval(heartTime);
var html = "<span style='color:red'>客户端断开连接</span></br>"
$("#toke").append(html);
}
// 服务器发生异常
ws.onerror = function(){
var html = "<span style='color:red'>服务器异常</span></br>"
$("#toke").append(html);
}
ws.onmessage = function(data){
// 判断服务端返回的值是否为心跳返回值
if(data.data == "pong"){
return;
}
var html = "<span>服务器:"+ data.data +"</span></br>"
$("#toke").append(html);
}
} else{
alert("当前浏览器不支持WebSocket!");
}
$("#send").click(function(){
var msg = $("#con").val();
ws.send(msg);
msg = "<span style='color:blue;display:block;text-align:right;margin-right:5px'>"+ msg +"</span></br>";
var showMsg = $("#toke");
showMsg.append(msg);
$("#con").val("");
});
function sendHeart(){
heartTime = setInterval(function(){
ws.send("ping");
},5000);
}
})
</script>
<body>
<div id="toke" style="width: 400px; height: 300px;border: 1px solid #f00;">
</div>
<input type="text" name="con" id="con" width="100px" />
<button id="send">发送</button>
</body>
</html>
二、服务端的核心代码
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private final String PING = "ping";
private final String PONG = "pong";
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
String text = textWebSocketFrame.text();
// 心跳,接收到的是ping,返回报文pong
if(PING.equals(text)){
channelHandlerContext.writeAndFlush(new TextWebSocketFrame(PONG));
}
}
}
网友评论