我目前正在开发一个实时短信系统,但我相当肯定我目前的实施是一个糟糕的做法,我正在寻找指导,以提高效率。
目前,当您加载界面时,它会提取您选择的该号码的所有短信。然后它每5秒触发一次ajax调用到我写的Twilio JSON PHP脚本,询问比列表中最后一条消息更新的消息。
$.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 :(得分:2)
Twilio开发者传道者在这里。
我不建议轮询Twilio API以获得&#34;实时&#34;短信息。轮询是低效的,并且会使您的服务器以及Twilio的服务器忙碌的时间超过必要的时间。
相反,我会使用Twilio&#39; webhooks to receive messages。然后,当您在页面上接收消息时,我将实现服务器发送事件(see this article for an in depth description of SSE as well as example PHP code to implement)或Web套接字(这里是关于web sockets in PHP和library built as part of it的文章)为了将您从webhook收到的新邮件推送到您的页面。
让我知道这是否有帮助。