【问题标题】:PHP and Twilio Real-time?PHP 和 Twilio 实时?
【发布时间】:2017-05-02 11:47:26
【问题描述】:

我目前正在开发一个实时 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");
            }
        });
    }
}

【问题讨论】:

  • 代码审查请求在这里是题外话。此类问题有适当的SE site

标签: javascript php jquery twilio real-time


【解决方案1】:

这里是 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 套接字(这里有一篇关于 web sockets in PHPlibrary built as part of it 的文章),以便推送您收到的新消息webhook 到您的页面。

让我知道这是否有帮助。

【讨论】:

  • 谢谢。我将深入研究这篇文章,看看我能想出什么。 :)
  • 太棒了,希望一切顺利!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多