1

所以我已经能够使用 AJAX 反复刷新我网站上的 div,使用以下代码:

var $container = $("#content");
    var refreshId = setInterval(function()
    {
        $container.load('toad.php').fadeOut("slow").load('response.php').fadeIn("slow"); ;
    }, 2000);

这工作正常,toad.php 每 2 秒执行一次并且内容更新。

toad.php 目前包含以下代码:

<?php 
if ( !($sock = socket_create(AF_INET, SOCK_STREAM, 0)) ) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);

        die("Couldn't create socket: [$errorcode] $errormsg \n");
    }

    echo "Socket created \n";

    if (!socket_connect($sock, '127.0.0.1', 45000)) {
        //$errorcode = socket_last_error();
        //$errormsg = socket_strerror($errorcode);
        echo "No sensor available to connect to.\n";
        //die("Could not connect: [$errorcode] $errormsg \n");
    }

    echo "Connection established \n";

    //Now receive reply from server
    if (false !== ($bytes = socket_recv($sock, $buf, 1200, MSG_WAITALL))) {
        echo "Read $bytes bytes from socket_recv(). Closing socket...";
    }           
    else {
         echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    }

    socket_close($sock);

    echo $buf . "\n";
    echo "OK.\n"; 
?>   

这样做的问题是,每次刷新 div 时都会创建并连接到套接字。

如果我在 toad.php 中没有 socket_create 和 socket_connect 函数,那么 socket_recv 函数不知道套接字并且不起作用。

我的问题是如何让套接字接收代码循环并更新 div 的内容,而不必每次都重新创建和连接到套接字?

谢谢!

4

1 回答 1

0

If you can rewrite the server your connecting to to use websocket, you could just connect directly from the browser using socket.io.

http://socket.io/

As others have said, maintaining a persistent PHP connection can be tricky, but if running a NodeJS (or similar) script to handle client connections isn't possible you could serve the websockets from that same PHP script.

Try this approach:

http://devzone.zend.com/209/writing-socket-servers-in-php/

Your toad.php script would run on the command line, listening to your existing socket server, then serving the data to it's own socket server which the browser connects to directly with websocket.

于 2013-07-25T10:02:59.603 回答