phpimagenetwork-programmingpackets

Sending large packets using php using socket_write


I am trying to encode an image to base64 encoding and send it to a C++ server I am creating. I am using PHP to do that.

Therefore, the PHP code is the client and the C++ code is the listening server.

The problem occurs on large images; for example 70KB images. It is working properly on small images; such as 5KB.

The error occurring is: Warning: socket_write() [function.socket-write]: unable to write to socket [0]: A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself.

Can this problem be fixed without dividing the image into several small packets?

I only need the sending packet to be 1MB.

This is the code I am using:

$con=file_get_contents("image url");
$binary_data=base64_encode($con);
$host = "192.168.35.54";
$port = 1060;
$message = $binary_data;
// No Timeout 
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Could not create socket\n");
socket_connect($socket, $host, $port) or die("Could not connect to server\n");
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");

Solution

  • There are a number of possible problems you could have. I assume you're using TCP. I'm also assuming you're writing the entire image in one call to socket_write. My first guess would be that the problem is one the receiving side. When you read the socket on the receiving side, you're not guarantted to get the entire block of data in one read. Normally, when reading TCP sockets, you read in a loop and accumulate the data that way until you've gotten all the data you're expecting, or you get an error.

    You can see some example code in this other SO post:

    Read from socket: Is it guaranteed to at least get x bytes?

    EDIT

    After seeing these additional details, my first suggestion would be to switch to TCP. You can do a single send that way, and then read in a loop on the receiving side like in the example code above. Otherwise, you'll have to break up the packet, and build in your own error detection code to make sure all the pieces arrive, plus put in sequence codes to reassemble them in order, which is basically just duplicating a bunch of functionality TCP already provides.