【问题标题】:Unable to capture response of PHP Sockets Connection :: 504 Gateway Time-out无法捕获 PHP 套接字连接的响应 :: 504 Gateway Time-out
【发布时间】:2014-04-01 23:31:39
【问题描述】:

我正在使用以下 php 代码通过 php sockets 连接连接并向远程服务器发送请求。

<?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\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
stream_set_timeout($socket, 10);
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
//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);
?>

正如确认的那样,远程机器正在接收我们的请求并在同一会话中向我们发送适当的响应。但不幸的是,执行脚本时我收到以下响应 -

504 网关超时。服务器没有及时响应。

当从 Putty(执行代码的同一服务器)尝试时,我几乎立即(不到一秒)得到响应。

没有运行会阻止响应的防火墙。如 telnet 请求和响应所示,所有 VPN 流量都通过隧道,没有任何阻塞。

现在我无法弄清楚没有通过这个 php 脚本获得响应的确切原因。我浏览了许多教程和示例代码,但没有找到运气。 :(

会员,请帮忙。

【问题讨论】:

    标签: php sockets telnet firewall php-socket


    【解决方案1】:

    我曾使用 php 套接字来模拟远程登录会话,而无需设置超时参数。试试下面的,让我知道进展如何

    <?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 \n 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);
    

    【讨论】:

      【解决方案2】:

      这可能已经过时,但The PHP manual 上的注释说:

      如果有人感到困惑,stream_set_timeout 不适用于使用 socket_create 或 socket_accept 创建的套接字。请改用 socket_set_option。

      代替:

      <?php
      stream_set_timeout($socket,$sec,$usec);
      ?>
      

      用途:

      <?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));
      ?>
      

      【讨论】:

      • 更新代码后,脚本仍未捕获远程服务器发送的响应并超时。
      【解决方案3】:

      尝试将socket_read中的读取模式设置为PHP_NORMAL_READ

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-28
        • 2021-05-12
        • 2021-08-10
        • 1970-01-01
        • 2012-10-09
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多