0

I'm using a socket to transmit a compressed file, but the file size for sending are different from that of reception.

This is server:

<?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";
    }
}
?>

This is client:

<?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";
    }
}
?>

But this are 2 message, on client:

Send text of 3741477 size

And this is on server:

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

So why even though the protocol is TCP, you lose the data that is not retransmitted? What's wrong?

Andrea
  • 265
  • 1
  • 3
  • 13

1 Answers1

0

Look at the PHP pages of socket_write

socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

About the socket_read it could be possible you have to call it many times and concat the chunks of data until no more data to read is present

Davide Berra
  • 6,387
  • 2
  • 29
  • 50