我想要实现的是逐行读取套接字,并将它们保存到文本文件中。
我使用过socket_recv和socket_read。我可以查看页面上的输出,但是当我保存输出时,它的垃圾。充满了字符串和垃圾二进制的东西。
我知道原因是因为接收数据的长度。但是没有办法知道我将收到多少。
我使用了网络上的一个例子
$str = "";
while($read = socket_read($sock, 3,PHP_NORMAL_READ)) {
$str .= $read;
if (strpos($str, "\n") !== false) break; // this stops the loop when a new line is encountered, how to restart the loop and read the rest of the lines
}
echo "Server said: $str";
//echo $this->_buffer;
$output = $str;
//echo "This much bytes ".strlen($this->_buffer);
$file = 'log.txt';
$handle = fopen($file,"a") or die("Could not open file for writing");
fwrite($handle,$output) or die("Could not write");
fclose($handle);
此代码段会将一行保存到文本文件中,但我有大约3行要接收。
如何让这个循环读取所有接收行并将它们写入文本文件。