正常创建一个连接,在一段时间后心跳就会因为接收不到数据而强制停止。从而断开连接,那么无论是前端还是后端都应该有自己的实现重连机制。这里写一个关于前端实现重连的机制:
代码如下:
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chat Example Using STOMP Over WebSockets</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap.min.responsive.css" rel="stylesheet">
<style type="text/css">
body { padding-top: 40px; }
</style>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="#">Stomp Over WebSocket Chat Example</a>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="span6">
<div id="connect">
<div class="page-header">
<h2>Server Login</h2>
</div>
<form class="form-horizontal" id='connect_form'>
<fieldset>
<div class="control-group" style="display:none">
<label>WebSocket URL</label>
<div class="controls">
<input name=url id='connect_url' value='ws://127.0.0.1:61613' type="text">
</div>
</div>
<div class="control-group" style="display:none">
<label>User</label>
<div class="controls">
<input id='connect_login' placeholder="User Login" value="admin" type="text">
</div>
</div>
<div class="control-group">
<label>ID</label>
<div class="controls">
<input id='connect_id' placeholder="ID" value="" type="text">
</div>
</div>
<div class="control-group">
<label>Password</label>
<div class="controls">
<input id='connect_passcode' placeholder="User Password" value="password" type="password">
</div>
</div>
<div class="control-group">
<label>Destination</label>
<div class="controls">
<input id='destination' placeholder="Destination" value="world" type="text">
</div>
</div>
<div class="form-actions">
<button id='connect_submit' type="submit" class="btn btn-large btn-primary">Connect</button>
</div>
</fieldset>
</form>
</div>
<div id="connected" style="display:none">
<div class="page-header">
<h2>Chat Room</h2>
</div>
<div id="messages">
</div>
<form class="well form-search" id='send_form'>
<button class="btn" type="button" id='disconnect' style="float:right">Disconnect</button>
<input class="input-medium" id='send_form_input' placeholder="Type your message here" class="span6"/>
<button class="btn" type="submit">Send</button>
</form>
</div>
</div>
<div class="span4">
<div class="page-header">
<h2>Debug Log</h2>
</div>
<pre id="debug"></pre>
</div>
</div>
</div>
<!-- Scripts placed at the end of the document so the pages load faster -->
<script src='js/jquery-1.7.2.min.js'></script>
<script src="js/stomp2.3.3.js"></script>
<script>//<![CDATA[
//定义全局变量,表明一个session
var client = null;
const data = new Map();
function connect(){ //定义链接函数
if(client == null || !client.connected){
//var url = 'http://localhost:8164/websocket';
//var url = '/websocket';
var headers={
'login':data.get('login'),
'passcode':data.get('passcode'),
'client-id': data.get('id')
};
client = Stomp.client(data.get('url'));
client.connect(headers, connectCallback ,errorCallback );
}else{
$("#debug").append("当前处于链接状态" + "\n");
}
}
function connectCallback (frame) { //链接成功时的回调函数
client.subscribe('world', function (result) {
var content = result.body;
$("#messages").append('<p>'+content+'</p>' + "\n");
}, {});
}
function errorCallback(){//链接失败时的回调函数,此函数从新调用链接方法,造成循环,直到链接成功
connect();
var d = new Date();
console.log(d.getDate()+d.getHours()+d.getMinutes()+"执行了重连。。。");
}
$(document).ready(function() {
if(window.WebSocket) {
$('#connect_form').submit(function() {
data.set('url',$("#connect_url").val());
data.set('login',$("#connect_login").val());
data.set('passcode',$("#connect_passcode").val());
data.set('id',$("#connect_id").val());
connect();//创建链接
$('#connect').remove();
$('#connected').css('display','');
// this allows to display debug logs directly on the web page
//client.debug = function(str) {
//$("#messages").append("<p>" +str.body+ "</p>" +"\n");
//$("#debug").append(str + "\n");
// };
return false;
});
$('#disconnect').click(function() {
client.disconnect(function() {
$('#connected').fadeOut({ duration: 'fast' });
$('#connect').fadeIn();
$("#messages").html("")
});
location.reload ();
return false;
});
$('#send_form').submit(function() {
var text = $('#send_form_input').val();
if (text) {
client.send('world', {}, text);
$('#send_form_input').val("");
}
return false;
});
} else {
$("#connect").html("\
<h1>Get a new Web Browser!</h1>\
<p>\
Your browser does not support WebSockets. This example will not work properly.<br>\
Please use a Web Browser with WebSockets support (WebKit or Google Chrome).\
</p>\
");
}
});
//]]></script>
</body>
</html>
实现原理很简单,使用stomp进行连接,里面定义了连接方法client.connect(headers, connectCallback ,errorCallback );分别是头信息,连接成功回调,和连接失败回调,
底层实现的是windows.setinterval()方法进行定时检测连接是否正常。这样服务启动后就会一直有正常的连接支持。遗憾的是这种连接方法并不能使同一个sessionid的连接重连。而是取到我们填写的信息再次连接。