[英]PHP and Twilio Real-time?
我目前正在開發一個實時SMS系統,但是我對當前的實現是一個糟糕的做法感到非常肯定,並且我正在尋找可以提高效率的指南。
當前,當您加載界面時,它會拉出所選號碼的所有文本消息。 然后,它每隔5秒觸發對我編寫的Twilio JSON PHP腳本的ajax調用,以詢問比列表中的最后一條消息新的消息。
$.getJSON("/includes/twilio.php",{action:"getconvo",cid:customer.customer_number},function(data){
$('#sms_messages').html("<div></div>");
$(data.messages).each(function(){
insertSMS(this.msg,this.date,this.from);
lastMessage = this.date;
});
$("#sms_messages").animate({ scrollTop: $('#sms_messages > div').height()},"fast");
shouldUpdate = true;
sms_interval = setInterval(function(){updateSMS(customer.customer_number)},5000);
});
更新功能
function updateSMS(cid){
if(shouldUpdate){
$.getJSON("/includes/twilio.php",{action:"getconvo",cid:cid,date:lastMessage},function(data){
if(data.messages.length > 0){
// Play an embeded sound effect when a new message is found.
$('#sms_sound')[0].play();
$(data.messages).each(function(){
insertSMS(this.msg,this.date,this.from);
lastMessage = this.date;
});
$("#sms_messages").animate({ scrollTop: $('#sms_messages > div').height()},"fast");
}
});
}
}
Twilio開發人員布道者在這里。
我不建議輪詢Twilio API以獲取“實時” SMS消息。 輪詢效率低下,會使您的服務器以及Twilio的服務器忙於不必要的時間。
相反,我會使用Twilio的webhooks來接收消息 。 然后,當您在頁面上接收消息時,我將實現服務器發送事件( 有關SSE的詳細說明以及要實現的示例PHP代碼,請參見本文 )或Web套接字(這是有關PHP中的Web套接字的文章)以及作為其中一部分構建的庫 ),以便將您從網絡掛鈎收到的新消息推送到您的頁面。
讓我知道是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.