Im opening up a connection to a server that accepts XML requests. I am required to send two requests one after the other.
If I run the first request on its own I get data back If I run the second request on its own I get data back
If I run both within a loop using the same connection, only the first request works, the second returns no data.
Is there something I need to send to the socket between each request to indecate the end of each request, otherwise what am I doing wrong?
// Open socket connection
$socket = pfsockopen($this->config['ip'], $this->config['port'], $errno, $errstr, 30);
// Try and open a connection
if ( ! $socket) {
throw new \Exception($errstr . '('.$errno.')');
}
// If connection was successfull start sending requests
else{
// Loop each request within the container
foreach($this->container as $key => $object){
print "Request" . ($key+1) . PHP_EOL;
// Reset data and post string
$data = array();
$xml_post_string = null;
// Create XML string
$xml = \LSS\Array2XML::createXML('request', $object->request);
$xml_post_string = $xml->saveXML();
// Add ending lines
$xml_post_string = $xml_post_string . PHP_EOL . PHP_EOL;
// Loop
fwrite($socket, $xml_post_string);
while ( ! feof($socket)) {
$data[] = fgets($socket, 1024);
}
// Tried adding, but fails
ftruncate($socket, 2);
if(count($data)){
print implode($data);
}
else{
print "No response from server - you broke it" . PHP_EOL;
}
}
}
fclose($socket);
A second attempt. The results are the same for any random server out there.
// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Connect the socket
socket_connect($socket, 'xxx.xxx.xxx.xxx', '80');
$xml_post_string_one = '<request><message>Hello first world</message></request>';
$xml_post_string_two = '<request><message>Hello second world</message></request>';
// FIRST ROUND //
// Send data to it
socket_write($socket, $xml_post_string_one, strlen($xml_post_string_one));
// Get data from it
socket_recv($socket, $bufA, 2048, MSG_WAITALL);
// Done
print strlen($bufA) . PHP_EOL; // Got info back
// SECOND ROUND //
// Send data to it
socket_write($socket, $xml_post_string_two, strlen($xml_post_string_two));
// Get data from it
socket_recv($socket, $bufB, 2048, MSG_WAITALL);
// Done
print strlen($bufB). PHP_EOL; // Returns 0, Why?