<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Websocket示例</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var heartbeat_timer = 0;
var last_health = -1;
var health_timeout = 3000;
$(function(){
//ws = ws_conn( "ws://211.100.41.186:9999" );
ws = ws_conn( "ws://127.0.0.1:5354");
$("#send_btn").click(function(){
var msg = $("#mysendbox").val();
ws.send( msg );
$("#mysendbox").val("");
});
});
function keepalive( ws ){
var time = new Date();
if( last_health != -1 && ( time.getTime() - last_health > health_timeout ) ){
//此时即可以认为连接断开,可是设置重连或者关闭
$("#keeplive_box").html( "服务器没有响应." ).css({"color":"red"});
//ws.close();
}
else{
$("#keeplive_box").html( "连接正常" ).css({"color":"green"});
if( ws.bufferedAmount == 0 ){
ws.send( 'HeartBeat'); }
}
}
//websocket function
function ws_conn( to_url ){
to_url = to_url || "";
if( to_url == "" ){
return false;
}
clearInterval( heartbeat_timer );
$("#statustxt").html("Connecting...");
var ws = new WebSocket( to_url );
ws.onopen=function(){
$("#statustxt").html("connected.");
$("#send_btn").attr("disabled", false);
heartbeat_timer = setInterval( function(){keepalive(ws)}, 5000 );
}
ws.onerror=function(){
$("#statustxt").html("error.");
$("#send_btn").attr("disabled", true);
clearInterval( heartbeat_timer );
$("#keeplive_box").html( "连接出错." ).css({"color":"red"});
}
ws.onclose=function(){
$("#statustxt").html("closed.");
$("#send_btn").attr("disabled", true);
clearInterval( heartbeat_timer );
$("#keeplive_box").html( "连接已关闭." ).css({"color":"red"});
}
ws.onmessage=function(msg){
var time = new Date();
if( msg.data == ( 'HeartBeat' ) ){
last_health = time.getTime();
return;
}
$("#chatbox").val( $("#chatbox").val() + msg.data + "\n" );
$("#chatbox").attr("scrollTop",$("#chatbox").attr("scrollHeight"));
}
return ws;
}
</script>
</head>
<body>
<p>web socket连接状态: <span id="statustxt">连接中...</span></p>
<p>心跳状态:<span id="keeplive_box">检测中...</span></p>
<p>
<textarea name="chatbox" id="chatbox" cols="55" rows="20" readonly="readonly"></textarea>
</p>
<p>
<p>发送文本到Websocket服务器</p>
<input name="mysendbox" type="text" id="mysendbox" size="50" />
<input type="button" name="send_btn" id="send_btn" value="Send" disabled="disabled" />
</p>
</body>
</html>