Sending lots of data over a TCP socket

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Bitmaster
Forum Newbie
Posts: 20
Joined: Thu Nov 21, 2002 8:42 am

Sending lots of data over a TCP socket

Post by Bitmaster »

I have a PHP page that sends some data through a TCP socket to another process on the web server. The amount of data can vary from 1 KB to about 10 MB. I know that a fwrite () call on a socket could return even if less than the requested amount has been transmitted (due to buffer availability on the TCP stack and the receiving end). I also know that a C function to send a block of data of a specified length looks like this:

Code: Select all

BOOL sendbuf (int socket, char *buf, int len)
{
   int sent;

   while (len > 0)
   {
       sent = send (socket, buf, len, 0 /* flags */);

       if (sent == -1)
          return (FALSE);

       len = len - sent;
       buf = buf + sent;
   }

   return (TRUE);
}
I need some help to translate the above function to PHP. So far what I have is this:

Code: Select all

function sendbuf ($socket, $buffer, $len)
{
   while ($len > 0)
   {
      $sent = fwrite ($socket, $buffer, $len);

   //error checking omitted for clairty

      $len = $len - $sent;		
      $buffer = substr ($buffer, $sent);  //this is a really bad way to skip over transmitted bytes	
   }	
}
This might work, but it is really memory inefficient for large buffers, since all data is copied several times over and over until it is transmitted.
Can anyone suggest a more efficient way to "advance" in a string and use it as a parameter to fwrite ?
Post Reply