http://javascript.ruanyifeng.com/htmlapi/websocket.html#toc7
項(xiàng)目實(shí)現(xiàn):實(shí)現(xiàn)web實(shí)時(shí)更新匹配人數(shù)。onError或onClose則提示刷新。

<code>
//websocket
varmatchId = {{.match_id}};
functionwebSocket() {
varwsUri ="{{.match_socket_url}}";
wsUri = wsUri+"?user_id="+userId+"&match_id="+matchId;
websocket=newWebSocket(wsUri);
showLoading(loadControl);
console.log(wsUri);
console.log("start1.....");
websocket.onopen=function(evt) {
onOpen(evt)
};
websocket.onmessage=function(evt) {
onMessage(evt);
};
websocket.onerror=function(evt) {
console.log("onError: "+evt);
createCookie("join_user_"+userId,"",-1);
hideLoading(loadControl);
$(".match-title").html("請刷新頁面獲取匹配進(jìn)度")
};
websocket.onclose=function(evt) {
console.log("onclose: "+evt);
createCookie("join_user_"+userId,"",-1);
hideLoading(loadControl);
$(".match-title").html("請刷新頁面獲取匹配進(jìn)度")
};
}
functiononOpen(evt) {
console.log("onOpen send start1.....");
websocket.send('{"user_id":"'+userId+'","match_id":"'+matchId+'"}');
console.log("onOpen send start2.....");
}
functiononMessage(evt) {
hideLoading(loadControl);
varjsonObject = JSON.parse(evt.data);
varbodyObj = JSON.parse(jsonObject.body);
varjoinUser = bodyObj.join_users;
varmatchFlag = bodyObj.match_flag;
console.log("joinUser:"+joinUser);
console.log("matchFlag:"+matchFlag);
createCookie("join_user_"+userId,joinUser,1);
setInterval(function() {
if(curJoinUser < joinUser) {
curJoinUser ++;
}
$(".green-ft").html(curJoinUser);
if(matchFlag ==1&& curJoinUser ==10){
createCookie("join_user_"+userId,"",-1);
window.location.reload();
}
},500);
}
</code>