I am using the following php code to connect and send a request to a remote server through php sockets connection.
<?php
$host = "X.X.X.X";
$port = 1234;
$message = "<request>test</request>";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket
");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server
");
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server
");
// get server response
stream_set_timeout($socket, 10);
$result = socket_read ($socket, 1024) or die("Could not read server response
");
//echo "Reply From Server :".$result;
$info = stream_get_meta_data($socket);
if (isset($info['timed_out']) && $info['timed_out'])
{
echo 'Connection timed out!';
}
else
{
var_dump($result);
}
// close socket
socket_close($socket);
?>
As confirmed, the remote machine is receiving our request and sending appropriate response to us over the same session. But unfortunately, I am getting the following response when the script is executed -
504 Gateway Time-out. The server didn't respond in time.
When tried from Putty (same server from where the code was executed), I am getting the response almost instantly (in less than a second).
There is no firewall running that would block the responses. All VPN traffic passes through the tunnel without any blocks as seen in telnet request and response.
Now I am unable to figure out the exact reason of not getting the response through this php script. I had gone through many tutorials and sample codes but found no luck. :(
Members, please help.
This might be outdated, but a note on The PHP manual says:
In case anyone is puzzled, stream_set_timeout DOES NOT work for sockets created with socket_create or socket_accept. Use socket_set_option instead.
Instead of:
<?php
stream_set_timeout($socket,$sec,$usec);
?>
Use:
<?php
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>$sec, 'usec'=>$usec));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>$sec, 'usec'=>$usec));
?>
I've worked with php socket that simulates a telnet session without setting a timeout parameter. Try the below and let me know how it well it goes
<?php
// You can use socket_strerror(socket_last_error()) to get the error details
$socket = socket_create(AF_INET,SOCK_STREAM,0) or die ('Could not create socket') ;
$result = socket_connect($socket,$host,$port) or die ('Could not connect to host');
// The server expects the enter key to pressed to execute the command which i simulate by
// appending a
to the message sent to the server
socket_send($socket,$message,strlen($message),0) or die('Could not execute command');
$result = socket_read($socket,2048) or die('Could not read from socket');
var_dump($result);
Try setting the read mode in socket_read to PHP_NORMAL_READ