我打开了与接受XML请求的服务器的连接。我被要求一个接一个地发送两个请求。
如果我自己运行第一个请求,我会收回数据 如果我自己运行第二个请求,我会得到数据
如果我使用相同的连接在循环内运行,只有第一个请求有效,第二个请求不返回数据。
我是否需要在每个请求之间向套接字发送一些内容,以便在每个请求的末尾进行分心,否则我做错了什么?
// 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);
第二次尝试。任何随机服务器的结果都是相同的。
// 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?