I am sending and receiving data using fsockopen and fwrite. My application receives the proper response, but seems to wait until some sort of timeout before continuing. I suspect that I am not closing the connection properly after it finishes receiving the response, which explains the wait. Could someone take a look at my code?
private static function Send($URL, $Data) {
$server = parse_url($URL, PHP_URL_HOST);
$port = parse_url($URL, PHP_URL_PORT);
// If the parsing the port information fails, we will assume it's on a default port.
// As such, we'll set the port in the switch below.
if($port == null) {
switch(parse_url($URL, PHP_URL_SCHEME)) {
case "HTTP":
$port = 80;
break;
case "HTTPS":
$port = 443;
break;
}
}
// Check if we are using a proxy (debug configuration typically).
if(\HTTP\HTTPRequests::ProxyEnabled) {
$server = \HTTP\HTTPRequests::ProxyServer;
$port = \HTTP\HTTPRequests::ProxyPort;
}
// Open a connection to the server.
$connection = fsockopen($server, $port, $errno, $errstr);
if (!$connection) {
die("OMG Ponies!");
}
fwrite($connection, $Data);
$response = "";
while (!feof($connection)) {
$response .= fgets($connection);
}
fclose($connection);
return $response;
}
The problem is with this line:
Sockets are streams; unless the other side closes the connection first,
feofwill never returntrueand your script will eventually time out.To perform an orderly shutdown both parties have to close their end of the connection; one of them can do it as a response to the other, but clearly if both are waiting for the other to close first then noone ever will.
Does the program on the other side close the connection after outputting something? It seems not.