2016-12-16 30 views
1

我目前正在研究一個實時SMS系統,但我相當積極,我目前的實施是一個可怕的做法,我正在尋找更有效的指導。PHP和Twilio實時?

的嘗試

目前,當你加載它拉一切爲您選擇該號碼的短信界面。然後,它每隔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"); 
      } 
     }); 
    } 
} 
+0

代碼審查請求在這裏是無關緊要的。這些問題有適當的[SE site](http://codereview.stackexchange.com/)。 – hindmost

回答

2

Twilio開發者傳道這裏。

我不建議輪詢Twilio API以獲取「實時」SMS消息。輪詢效率低下,並且會使服務器和Twilio的服務器保持忙碌狀態的時間超過必要的時間。

相反,我會使用Twilio的webhooks to receive messages。然後,當你在頁面上收到的消息我會實現無論是服務器發送的事件(see this article for an in depth description of SSE as well as example PHP code to implement)或網絡套接字(這裏的一對web sockets in PHP和文章library built as part of it),以推動您從網絡掛接到您的網頁接收新郵件。

讓我知道這是否有幫助。

+0

謝謝。我將深入這篇文章,看看我能想出什麼。 :) –

+0

太棒了,希望它順利! – philnash