http://javascript.ruanyifeng.com/htmlapi/websocket.html#toc7
项目实现:实现web实时更新匹配人数。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("请刷新页面获取匹配进度")
};
websocket.onclose=function(evt) {
console.log("onclose: "+evt);
createCookie("join_user_"+userId,"",-1);
hideLoading(loadControl);
$(".match-title").html("请刷新页面获取匹配进度")
};
}
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>
网友评论