如何完全实现服务器发送的事件以进行消息轮询 [英] How to fully implement server-sent events for message polling

查看:117
本文介绍了如何完全实现服务器发送的事件以进行消息轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用API​​与服务器进行通信。

I am trying to communicate with a server using an API.

使我更容易编写一个脚本,使用php脚本来传递API。

to make it easier I wrote a script that will communicate the API using a php script.

我的目标是每秒查询一次API,看看队列中是否有新消息。

My goal is to make a query to the API every second to see if there is new message in their queue.

我被建议使用服务器发送事件方法并让服务器只在有新内容时才向客户端发送响应。

I was advised to use server-sent events method and have the server send a respond to the client only when it has something new.

这是我的php脚本

<?php

    // Register autoloader function
    spl_autoload_register('apiAutoloader');
    header("Content-Type: text/event-stream\n\n");

    $config = array('host' => 'server:IP',              //REQUIRED - Server Name
                    'port' => 8018,                     //REQUIRED - Server Port
                    'userID' => 'user',                 //REQUIRED - UserID to login with
                    'password' => '123456',             //REQUIRED - password for the UserID to login with
                    );

    try {

        //create a new instance of icws
        $icws = new API\ICWS($config); 

        //create a new session
        $icws->createSession(true);     

        while(1){

            $result = $icws->processMessage();
            echo json_encode($result);  

            ob_flush();
            flush();
            sleep(1);

        }

    } catch(Exception $e){
        echo $e->getMessage();
    }

    function apiAutoloader($className)
    {
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';

        if ($lastNsPos = strripos($className, '\\')) 
        {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }

        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

        $toLoad = dirname(__FILE__).'/'.$fileName;

        if (is_file($toLoad) === true)
        {
            include $toLoad;
        }
    }
?>

当用户访问我的页面时,这是我运行的代码

When a user visit my page this is the code the I run

<script>

    $(function(){

        function isset(a, b){

            if(typeof a !== "undefined" && a){
                return a
            }

            return b;
        }


        var evtSource = new EventSource("poll.php");

        evtSource.onmessage = function(e) {

            $.each(e.data.calls, function(i, item){

                $.each(item, function(z, c){

                    var interactionId = isset(c.interactionId, 0);
                    var Eic_CallDirection = isset(c.Eic_CallDirection, '');
                    var Eic_State = isset(c.Eic_State, '');
                    var AccoRDI_mid = isset(c.AccoRDI_mid, '');
                    var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');

                    if(Eic_State == '' || Eic_CallDirection == ''){
                        return;
                    }

                    //incoming call that is not answered
                    if( Eic_CallDirection == 'I' && Eic_State == 'A'){
                        console.log('Incomming Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
                        return;
                    }

                    //on hold
                    if( Eic_State == 'H'){
                        console.log('Phone number ' + Eic_RemoteAddress + ' is on hold' );
                        return;
                    }

                    //voicemail
                    if( Eic_State == 'M'){
                        console.log('Phone number ' + Eic_RemoteAddress + ' is on leaving a voicemail' );
                        return;
                    }

                    //connected call
                    if(Eic_State == 'C'){
                        console.log('Live Call With ' + Eic_RemoteAddress );
                        return;
                    }

                    //Dialling call
                    if(Eic_State == 'O'){
                        console.log('Dialling ' + Eic_RemoteAddress );
                        return;
                    }

                    //Dialling call
                    if(Eic_State == 'R'){
                        console.log('Outbound call is rining and waiting for answer ' );
                        return;
                    }

                    //Call Disconnected
                    if(Eic_State == 'I' || Eic_State == 'E' ){
                        console.log('Hungup with ' + Eic_RemoteAddress );
                        return;
                    }

                });
            });
        }
    });
</script>

我的上述代码无效。

我的控制台里没有任何东西。但是这个错误 Firefox无法在/icws/poll.php与服务器建立连接

I don't get anything in my console. but this error Firefox can't establish a connection to the server at /icws/poll.php

怎么能我明白了吗?
我通过PHP脚本实现的方式是否正确?

How can I get it to work? Is the way I implemented by PHP script correct?

推荐答案

浏览器请求的状态代码是什么?事件源php文件?尝试使用firebug来确保它不是404。

What is the status code on the browser request for you event source php file ? Try to use firebug to make sure its not 404.

还关于php代码。

根据您提问中的Mozilla来源。
服务器的正确响应应该被命名并用换行符分隔

According to Mozilla source you included in your question. Proper response from server should be named and separated by newlines

header("Content-Type: text/event-stream\n\n");     
while (1) {     
  echo "event: ping\n"; //event name
  echo 'data: '.json(); //event data
  Echo "\n\n"; //required  

  ob_flush(); flush(); sleep(1);    
 }

事件示例

event: userconnect
data: {"username": "bobby", "time": "02:33:48"} 

event: usermessage
data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."} 

这篇关于如何完全实现服务器发送的事件以进行消息轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆