長鏈接通信

http://javascript.ruanyifeng.com/htmlapi/websocket.html#toc7

項(xiàng)目實(shí)現(xiàn):實(shí)現(xiàn)web實(shí)時(shí)更新匹配人數(shù)。onError或onClose則提示刷新。

image

<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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容