Your problem is almost certainly due to the fact that fwrite
operations on non-blocking socket streams can be interrupted by the arrival of new packets. As a result, you can't count on an fwrite
to be atomic. In such cases you MUST rely on the return value of your fwrite
invocation to tell you exactly how many bytes were written to the stream in that pass and continue writing until all your data is sent.
For example ...
$dataToWrite = 'my data';
$bytesToWrite = strlen($dataToWrite);
$totalBytesWritten = 0;
while ($totalBytesWritten < $bytesToWrite) {
$bytes = fwrite($mySock, substr($dataToWrite, $totalBytesWritten));
$totalBytesWritten += $bytes;
}
Obviously, a robust treatment of this problem must also account for situations where the socket connection goes away, etc.