繁体   English   中英

使用PHP处理程序在服务器发送的事件中数据丢失

[英]Data getting lost in server-sent event with PHP handler

我正在使用服务器发送的事件开发单向消息传递系统。 我有一个文件(server.html),它将textarea的内容发送到PHP文件(handler.php)。

function sendSubtitle(val) {
    var xhr = new XMLHttpRequest();
    var url = "handler.php";
    var postdata = "s=" + val;
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
    xhr.send(postdata);
    //alert(val);
}

这有效(alert(val)在文本区域中显示文本)。

我的handler.php代码如下所示:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$stringData = $_POST['s'];

echo "data: Data is {$stringData}\n\n";
flush();

我的SSE接收器文件(client.html)的相关部分如下:

if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("handler.php");
    source.onmessage = function(event) {
        var textarea = document.getElementById('subtitles');
        textarea.value += event.data + "<br>";
        textarea.scrollTop = textarea.scrollHeight;

    };
} else {
    document.getElementById("subtitles").value = "Server-sent events not supported.";
}

问题在于client.html仅显示“数据:数据为”,因此server.html中的文本在途中丢失了。 我以为是PHP代码崩溃了,但是我无法弄清楚出了什么问题。 如果有人可以提供帮助,我将不胜感激。

编辑

我选择使用SSE而不是websocket,因为我只需要单向通信:server.html每当更改时,应将其textarea的内容推送到client.html。 我看过(而且看过很多!)的SSE的所有示例都发送“自动”的基于时间的数据。 我还没有看到任何使用实时用户输入的东西。 因此,也许我应该澄清一下原来的问题,然后问:“每当用户在网页A中输入文本区域时,如何使用SSE更新网页B中的DIV(或其他内容)?”

UPDATE

我将问题缩小到PHP文件中的while循环,因此提出了一个新问题: 使用while循环时,服务器端PHP事件页面未加载

您第一次在server.html中调用了handler.php,然后在client.html中再次调用了。 两者是不同的过程。 可变状态不会保留在Web服务器中。 如果要在另一个PHP进程中使用该值,则需要将其存储在某个位置。 可能是您可以使用会话或数据库。

使用会话时,您可以将值存储在两个文件中,例如:

<?php
//server.php
session_start();
$_SESSION['s'] = $_POST['s'];

并在client.php中

<?php
//client.php
session_start();
echo "data: Data is ".$_SESSION['s']."\n\n";

假设您要从server.html发送一个值,并且client.html上的值将自动更新...

您将需要将新值存储在某个地方,因为脚本的多个实例不会像这样共享变量。 此新值可以存储在文件,数据库中或作为会话变量等。

脚步:

  1. 使用clientScript1将新值发送到phpScript1。
  2. 用phpScript1存储新值。
  3. 将clientScript2连接到phpScript2。
  4. 将存储的值发送到clientScript2(如果已更改)。

即时获取新值意味着phpScript2必须循环执行,并在clientScript1更改值时将消息发送到clientScript2。

当然,有更多和不同的方法来达到相同的结果。

下面是我在上一个项目中使用的暂存器中的一些代码。 大多数部分都来自一个类(正在开发中),所以我不得不采用很多代码。 另外,我尝试将其适合您的现有代码。 希望我没有引入任何错误。
请注意,我没有考虑您的价值的任何确认! 另外,代码没有经过调试或优化,因此尚未准备好投入生产。

客户端( 发送新值,例如您的代码):

function sendSubtitle(val) {
    var xhr = new XMLHttpRequest();
    var url = "handler.php";
    var postdata = "s=" + val;
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
    xhr.send(postdata);
    //alert(val);
}

服务器端( 存储新值):

<?php
session_start();
$_SESSION['s'] = $_POST['s'];

客户端( 获取新价值):

//Check for SSE support at client side.
if (!!window.EventSource) {
    var es = new EventSource("SSE_server.php");
} else {
    console.log("SSE is not supported by your client");
    //You could fallback on XHR requests.
}

//Define eventhandler for opening connection.
es.addEventListener('open', function(e) {
  console.log("Connection opened!");
}, false);

//Define evenhandler for failing SSE request.
es.addEventListener('error', function(event) {
    /*
     * readyState defines the connection status:
     * 0 = CONNECTING:  Connecting
     * 1 = OPEN:        Open
     * 2 = CLOSED:      Closed
     */
  if (es.readyState == EventSource.CLOSED) {
    // Connection was closed.
  } else {
      es.close(); //Close to prevent a reconnection.
      console.log("EventSource failed.");
  }
});

//Define evenhandler for any response recieved.
es.addEventListener('message', function(event) {
    console.log('Response recieved: ' + event.data);
}, false);

// Or define a listener for named event: event1
es.addEventListener('event1', function(event) {
    var response = JSON.parse(event.data);
    var textarea = document.getElementById("subtitles");
    textarea.value += response + "<br>";
    textarea.scrollTop = textarea.scrollHeight;
});

服务器端( 发送新值):

<?php
$id = 0;
$event = 'event1';
$oldValue = null;
session_start();

//Validate the clients request headers.
if (headers_sent($file, $line)) {
    header("HTTP/1.1 400 Bad Request");
    exit('Headers already sent in %s at line %d, cannot send data to client correctly.');
}
if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] != 'text/event-stream') {
    header("HTTP/1.1 400 Bad Request");
    exit('The client does not accept the correct response format.');
}

//Disable time limit
@set_time_limit(0);

//Initialize the output buffer
if(function_exists('apache_setenv')){
    @apache_setenv('no-gzip', 1);
}
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
while (ob_get_level() != 0) {
    ob_end_flush();
}
ob_implicit_flush(1);
ob_start();

//Send the proper headers
header('Content-Type: text/event-stream; charset=UTF-8');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // Disables FastCGI Buffering on Nginx

//Record start time
$start = time();

//Keep the script running
while(true){
    if((time() - $start) % 300 == 0){
        //Send a random message every 300ms to keep the connection alive.
        echo ': ' . sha1( mt_rand() ) . "\n\n";
    }

    //If a new value hasn't been sent yet, set it to default.
    session_start();
    if (!array_key_exists('s', $_SESSION)) {
        $_SESSION['s'] = null;
    }

    //Check if value has been changed.
    if ($oldValue !== $_SESSION['s']) {
        //Value is changed
        $oldValue = $_SESSION['s'];
        echo 'id: '    . $id++  . PHP_EOL;  //Id of message
        echo 'event: ' . $event . PHP_EOL;  //Event Name to trigger the client side eventhandler
        echo 'retry: 5000'      . PHP_EOL;  //Define custom reconnection time. (Default to 3000ms when not specified)
        echo 'data: '  . json_encode($_SESSION['s']) . PHP_EOL; //Data to send to client side eventhandler
        //Note: When sending html, you might need to encode with flags: JSON_HEX_QUOT | JSON_HEX_TAG
        echo PHP_EOL;
        //Send Data in the output buffer buffer to client.
        @ob_flush();
        @flush();
    }

    //Close session to release the lock
    session_write_close();

    if ( connection_aborted() ) {
        //Connection is aborted at client side.
        break;
    }
    if((time() - $start) > 600) {
        //break if the time exceeds the limit of 600ms.
        //Client will retry to open the connection and start this script again.
        //The limit should be larger than the time needed by the script for a single loop.
        break;
    }

    //Sleep for reducing processor load.
    usleep(500000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM