开发者问题收集

PHP 文本流/缓冲区在脚本之间共享实时数据

2019-06-14
1840

php stream_socket_server/client with Local File访问问题。

我正在使用此脚本的修改: php:如何保存客户端套接字(未关闭),因此进一步的脚本可以检索它以发送到发送答案吗? ,但我无法使本地文件部分正常工作。

我要做的是通过将文件用作中间 - 男人,本质上是流数据。

我在现有脚本上遇到麻烦,我正在打开/添加到现有文件中。

stream_socket_server 侧,它将工作一次(文件不存在),然后在任何后续尝试运行;

125996586

上抛出下面的错误。 > stream_socket_server 创建文件,它仅在下面的摘要中使用详细信息读取;

312413980

我尝试将权限调整为更宽容的东西,但是没有运气。

在插座客户端,我永远都无法打开该文件。

744042446 281357795
2个回答

首先,我先说一句:您确定需要 unix 套接字吗?您确定 proc_open() 的管道不足以实现您的目标吗? proc_open() 比 unix 套接字使用起来容易得多。继续,

注意事项: 不要相信 fread() 可以一次性读取所有数据, 特别是 在发送大量数据(如兆字节)时,您需要某种方式来传达消息的大小,这可以通过在所有消息的开头添加消息长度标头来实现,例如 little-endian uint64 字符串,您可以使用

/**
 * convert a native php int to a little-endian uint64_t (binary) string
 *
 * @param int $i
 * @return string
 */
function to_little_uint64_t(int $i): string
{
    return pack('P', $i);
}

生成该标头,您可以使用

/**
 * convert a (binary) string containing a little-endian uint64_t
 * to a native php int
 *
 * @param string $i
 * @return int
 */
function from_little_uint64_t(string $i): int
{
    $arr = unpack('Puint64_t', $i);
    return $arr['uint64_t'];
}

解析它,有时 fread() 不会在第一次调用中返回所有数据,您必须继续调用 fread() 并附加数据以获取完整消息,下面是此类 fread() 循环的实现:

/**
 * read X bytes from $handle,
 * or throw an exception if that's not possible.
 *
 * @param mixed $handle
 * @param int $bytes
 * @throws \RuntimeException
 * @return string
 */
function fread_all($handle, int $bytes): string
{
    $ret = "";
    if ($bytes < 1) {
        // ...
        return $ret;
    }
    $bytes_remaining = $bytes;
    for (;;) {
        $read_now = fread($handle, $bytes_remaining);
        $read_now_bytes = (is_string($read_now) ? strlen($read_now) : 0);
        if ($read_now_bytes > 0) {
            $ret .= $read_now;
            if ($read_now_bytes === $bytes_remaining) {
                return $ret;
            }
            $bytes_remaining -= $read_now_bytes;
        } else {
            throw new \RuntimeException("could only read " . strlen($ret) . "/{$bytes} bytes!");
        }
    }
}

此外,在发送大量数据,你也不能信任 fwrite(),有时你需要调用 fwrite,看看它写了多少字节,然后 substr() - 截断实际写入的字节,并在第二个 fwrite() 中发送其余部分,依此类推,这里有一个 fwrite() 循环的实现,它一直写入直到所有内容都写入(如果不能写入所有内容,则引发异常):

/**
 * write the full string to $handle,
 * or throw a RuntimeException if that's not possible
 *
 * @param mixed $handle
 * @param string $data
 * @throws \RuntimeException
 */
function fwrite_all($handle, string $data): void
{
    $len = $original_len = strlen($data);
    $written_total = 0;
    while ($len > 0) {
        $written_now = fwrite($handle, $data);
        if ($written_now === $len) {
            return;
        }
        if ($written_now <= 0) {
            throw new \RuntimeException("could only write {$written_total}/{$original_len} bytes!");
        }
        $written_total += $written_now;
        $data = substr($data, $written_now);
        $len -= $written_now;
        assert($len > 0);
    }
}

.. 有了这些,你可以创建你的服务器,如

$server_errno = null;
$server_errstr = "";
$server_path = __FILE__ . ".socket";
$server = stream_socket_server("unix://" . $server_path, $server_errno, $server_errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
if (! $server || ! ! $server_errno) {
    throw new \RuntimeException("failed to create server {$server_path} - errno: {$server_errno} errstr: {$server_errstr}");
}
register_shutdown_function(function () use (&$server_path, &$server) {
    // cleanup
    fclose($server);
    unlink($server_path);
});
var_dump("listening on {$server_path}", $server);

现在如果你只需要支持与 1 个客户端对话,只需一条消息,就可以做到

echo "waiting for connection...";
$client = stream_socket_accept($server);
echo "connection!\n";
echo "reading message size header..";
stream_set_blocking($client, true);
// size header is a little-endian 64-bit (8-byte) unsigned integer
$size_header = fread_all($client, 8);
$size_header = from_little_uint64_t($size_header);
echo "got size header, message size: {$size_header}\n";
echo "reading message...";
$message = fread_all($client, $size_header);
echo "message recieved: ";
var_dump($message);
$reply = "did you know that the hex-encoded sha1-hash of your message is " . bin2hex(hash("sha1", $message, true)) . " ?";
echo "sending reply: {$reply}\n";
fwrite_all($client, to_little_uint64_t(strlen($reply)) . $reply);
echo "reply sent!\n";

客户端可能看起来像

$unix_socket_path = __DIR__ . "/unixserver.php.socket";
$conn_errno = 0;
$conn_errstr = "";
echo "connecting to unix socket..";
$conn = stream_socket_client("unix://" . $unix_socket_path, $conn_errno, $conn_errstr, (float) ($timeout ?? ini_get("default_socket_timeout")), STREAM_CLIENT_CONNECT);
if (! $conn || ! ! $conn_errno) {
    throw new \RuntimeException("unable to connect to unix socket path at {$unix_socket_path} - errno: {$conn_errno} errstr: {$conn_errstr}");
}
stream_set_blocking($conn, true);
echo "connected!\n";
$message = "Hello World";
echo "sending message: {$message}\n";
fwrite_all($conn, to_little_uint64_t(strlen($message)) . $message);
echo "message sent! waitinf for reply..";
$reply_length_header = fread_all($conn, 8);
$reply_length_header = from_little_uint64_t($reply_length_header);
echo "got reply header, length: {$reply_length_header}\n";
echo "reciving reply..";
$reply = fread_all($conn, $reply_length_header);
echo "recieved reply: ";
var_dump($reply);

现在运行我们得到的服务器:

hans@dev2020:~/projects/misc$ php unixserver.php 
string(59) "listening on /home/hans/projects/misc/unixserver.php.socket"
resource(5) of type (stream)
waiting for connection...

然后运行客户端,

hans@dev2020:~/projects/misc$ php unixclient.php 
connecting to unix socket..connected!
sending message: Hello World
message sent! waitinf for reply..got reply header, length: 105
reciving reply..recieved reply: string(105) "did you know that the hex-encoded sha1-hash of your message is 0a4d55a8d778e5022fab701977c5d840bbc486d0 ?"

现在回顾我们的服务器,我们会看到:

hans@dev2020:~/projects/misc$ php unixserver.php 
string(59) "listening on /home/hans/projects/misc/unixserver.php.socket"
resource(5) of type (stream)
waiting for connection...connection!
reading message size header..got size header, message size: 11
reading message...message recieved: string(11) "Hello World"
sending reply: did you know that the hex-encoded sha1-hash of your message is 0a4d55a8d778e5022fab701977c5d840bbc486d0 ?
reply sent!

这每次只对 1 个客户端有效,并且只有一个回复/响应,但是至少它正确使用了 fread/fwrite 循环,并确保无论消息有多大,始终完整发送/接收。

让我们做一些更有趣的事情:创建一个可以与无限数量的客户端异步通信的服务器

// clients key is the client-id, and the value is the client socket
$clients = [];

stream_set_blocking($server, false);
$check_for_client_activity = function () use (&$clients, &$server): void {
    $select_read_arr = $clients;
    $select_read_arr[] = $server;
    $select_except_arr = [];
    $empty_array = [];
    $activity_count = stream_select($select_read_arr, $empty_array, $empty_array, 0, 0);
    if ($activity_count < 1) {
        // no activity.
        return;
    }
    foreach ($select_read_arr as $sock) {
        if ($sock === $server) {
            echo "new connections! probably..";
            // stream_set_blocking() has no effect on stream_socket_accept,
            // and stream_socket_accept will still block when the socket is non-blocking,
            // unless timeout is 0, but if timeout is 0 and there is no waiting connections,
            // php will throw PHP Warning: stream_socket_accept(): accept failed: Connection timed
            // so it seems using @ to make php stfu is the easiest way here
            $peername = "";
            while ($new_connection = @stream_socket_accept($server, 0, $peername)) {
                socket_set_blocking($new_connection, true);
                $clients[] = $new_connection;
                echo "new client! id: " . array_key_last($clients) . " peername: {$peername}\n";
            }
        } else {

            $client_id = array_search($sock, $clients, true);
            assert(! ! $client_id);
            echo "new message from client id {$client_id}\n";
            try {
                $message_length_header = fread_all($sock, 8);
                $message_length_header = from_little_uint64_t($message_length_header);
                $message = fread_all($sock, $message_length_header);
                echo "message: ";
                var_dump($message);
            } catch (Throwable $ex) {
                echo "could not read the full message, probably means the client has been disconnected. removing client..\n";
                // removing client
                stream_socket_shutdown($sock, STREAM_SHUT_RDWR);
                fclose($sock);
                unset($clients[$client_id]);
            }
        }
    }
};
for (;;) {
    // pretend we're doing something else..
    sleep(1);
    echo "checking for client activity again!\n";
    $check_for_client_activity();
}

现在只需在方便的时候调用 $check_for_client_activity(); 来查看您是否有来自任何客户端的消息。如果您无事可做,想要等到收到任何客户端的消息,您可以这样做

$empty_array = [];
$select_read_arr=$clients;
$select_read_arr[]=$server;
$activity_count = stream_select($select_read_arr, $empty_array, $empty_array, null, null);

但是请注意,由于 stream_select() 的最后 2 个参数为空,如果您没有获得任何新连接并且任何客户端都没有发生任何事情, stream_select 可能会无限期阻塞 。(您可以设置另一个超时时间,例如 1 秒或其他时间,以设置超时时间。null 表示“永远等待”)

hanshenrik
2020-04-17

实际上有很多原因导致您无法实现这一点。

  • 首先,为了使事情变得简单,请使用不以“。”开头的文件,这样它就不会隐藏在您的查找器/终端中。
  • 然后,确保每次运行脚本后都删除套接字文件。 您可以在脚本中使用 unlink() 或手动 rm temp.sock 执行此操作 如果您不这样做,则无法创建套接字服务器,因为它已经存在。

您可能认为它不起作用,但实际上它确实有效: - !preg_match('/\r?\n\r?\n/', $buffer) 这种情况会阻止缓冲区在您的持久脚本中输出,因为它会等待这个双回车符到达套接字以打印所有内容。因此数据可能会进入套接字并在持久脚本中读取,但不会回显到响应中。

不能花太多时间在这上面,但这里有两个可以工作的文件的版本。确保在 senddata.php 之前运行 persist.php

persist.php

<?php 

$socket = stream_socket_server('unix://unique.sock', $errno, $errstr);

if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    $buffer = "";
    while (false === strpos($buffer, 'QUIT')) {
        $buffer .= fread($conn, 2046); 
    }
    echo $buffer;      
    flush();

    // Respond to socket client
    fwrite($conn,  "200 OK HTTP/1.1\r\n\r\n");
    fclose($conn);
    break;
  }
  fclose($socket);
  unlink('unique.sock');
}

senddata.php

<?php 

$sock = stream_socket_client('unix://unique.sock', $errno, $errstr);
if (false == $sock) {
    die('error');
}
while ($data = fgets(STDIN)) {
    fwrite($sock, $data);
    fflush($sock);  
}

fclose($sock);  

不确定您希望在哪种情况下使用它。但这可以帮助您了解如何使用套接字。 如果您不需要疯狂的快速性能,或者如果您更适合网络环境,我建议您切换并使用 WebSockets。

您可以在这里找到一个很棒的库: http://socketo.me/

这是现代的和面向对象的。 希望它能有所帮助。

maxleroy
2020-04-14