PHP套接字,发送和接收之间的消息长度不同


PHP socket, different message length between sending and receiving

我使用套接字传输压缩文件,但发送的文件大小与接收的文件大小不同。

这是服务器:

<?php
$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("socket_create() fallito: motivo: " . socket_strerror($this->sock) . "'n");
$ret = socket_bind($sock, "192.168.1.40", "9000") or die("socket_bind() fallito: motivo: " . socket_strerror($ret) . "'n");
$ret = socket_listen($this->sock) or die("socket_listen() fallito: motivo: " . socket_strerror($ret) . "'n");
while(true){
    if($buf = @socket_accept($this->sock)){
        echo "Call incoming'n";
        // Read lenght of file
        $lun = socket_read($buf, 1024);
        // Write ok
        socket_write($buf, "OkContinue", 1024) or die("Could not send data to server'n");
        // Read file of lenght $lun
        $lettura = socket_recv ($buf, $lun);
        // Write dimension
        echo "I need rec file of $lun size, but i rec: ".strlen($lettura)." size";
    }
}
?>

这是客户:

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket'n");
$result = socket_connect($socket, "192.168.1.40", "9000") or die("Could not connect to server'n");  
socket_write($socket, strlen($message), 1024) or die("Could not send data to server'n");
while ($out = socket_read($socket, 1024)) {
    if ($out=="OkContinue"){
        socket_write($socket, $message, strlen($message)) or die("Could not send data to server'n");
        echo "Send text of ".strlen($message)." size";
    }
}
?>

但这是客户端上的2条消息:

Send text of 3741477 size

这是在服务器上:

Call incoming
I need rec file of 3741477 size, but i rec: 82536 size

那么,为什么即使协议是TCP,你也会丢失未重新传输的数据呢?怎么了?

查看socket_write 的PHP页面

socket_write()不一定要写入给定缓冲器根据网络缓冲区等,只有通过缓冲区写入一定数量的数据,甚至是一个字节更大。你必须小心,以免无意中忘记以传输您的其余数据。

关于socket_read,您可能需要多次调用它并连接数据块,直到没有更多的数据可供读取