仅获取流的第一个字节

仅获取流的第一个字节

本文介绍了PHP socket_read()仅获取流的第一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中使用socket_read()时,我的行为很奇怪.

I'm getting a very weird behavior when using socket_read() in linux.

我正在使用具有2048个缓冲区限制的socket_read.

I'm using socket_read with a 2048 buffer limit.

在Windows系统上,它获得整个响应,而在Linux服务器上,它仅获得响应的第一个字节.

While on my windows system it gets the whole response, on my Linux server it just gets the first byte of the response.

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_connect($sock, 'my-server.dyndns.org', 8888)) {
   die('no connect');
}

$req = 'request';
socket_write($sock, $req);

if (false !== ($buf = socket_read($sock, 2048)) {
    echo $buf; // This only contains the first byte of the response.
}

socket_close($sock);

如果我再次调用socket_read(),它将获得字符串的其余部分:

If I call socket_read() again it gets the rest of the string:

// This works:

while((false !== ($buf = socket_read($sock, 2048)))) {
    echo "Read ".strlen($buf)." bytes from socket_read().\n";
    if ($buf == "") break;
    $b .= $buf;
    sleep(1);
}

/* Output:
 *
 * Read 1 bytes from socket_read().
 * Read 307 bytes from socket_read().
 * Read 0 bytes from socket_read().
 * Done.
 */

如果我在调用socket_read()之前等待2秒钟,也会得到一个有效的响应:

If I wait for 2 seconds before calling socket_read(), I also get a valid response:

// This also works:

sleep(2);
if (false !== ($buf = socket_read($sock, 2048)) {
    echo $buf; // all 308 bytes are read correctly.
}

socket_read()是否要等待缓冲区变满或字符串结尾?

Shouldn't socket_read() wait for the buffer to get full, or for the end of string?

我在做什么错了?

推荐答案

您需要量化整个响应".

You need to quantify "the whole response".

如果用整个响应"来表示,在关闭套接字之前将所有数据写入套接字,那么您需要使用一个循环来获取更多数据.recv不能保证在单个块中发送所有数据.

If by "the whole response", you mean, all the data that is written to the socket before it is closed, then you need to use a loop getting more data. recv is not guaranteed to send all the data in a single chunk.

我强烈建议您不要使用古老的socket_函数,而应使用fsockopen和fread.

I would strongly recommend that you don't use the ancient socket_ functions, but instead the fsockopen and fread instead.

这篇关于PHP socket_read()仅获取流的第一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:44