socket_read hanging in PHP



  • The problem is the next, after recording the data in the pokette, the function socket_read tries to count the data and hangs. It's harder to call jealousy, but it's rather an endless wait. Even if the time set_time_limit(3) is limited, the violin will not end in three seconds.

    It's going to be okay, returning the number of whites.

    Here's the code. The address and the port of the server are clearly secret. Tell me, is everything right in the code?

    $requestXml = '<?xml version="1.0" encoding="UTF-8"?><test><query></query></test>';
    

    // Подключение к сокету
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if(!socket_connect($socket, "000.000.000.000", 11111))
    die('Socket connect error: ' . socket_last_error());

    $size = socket_write($socket, $requestXml, 100);
    if(!$size)
    die('Socket send error: ' . socket_last_error());

    $responseHeaders = socket_read($socket, 1, PHP_NORMAL_READ);

    var_dump($responseHeaders);

    There's a Java program that's doing the same thing with the same data, it's getting the data straight.



  • Like the commentary, I faced a similar situation where the server could not close the connection, but also might not end the line. I've solved this problem with my time to get the data. This part of the code:

    class TcpClient {
        // ...
        private $_tryEof = 0;
        private $_maxTryEof = 20;
        private $_lastBufSize = 0;
        // ...
        private function _connect()
        {
            $this->_handler = stream_socket_client($this->_remoteSocket, $this->_errNo, $this->_errStr, $this->_timeout);
            // ...
        }
        private function _feof($eofStr)
            {
                $bufSize = strlen($this->buf);
                if ($this->_lastBufSize === $bufSize) {
                    $this->_tryEof++;
                    if ($this->_tryEof > $this->_maxTryEof) {
                        $this->_disconnect();
                    }
                }
            }else{
                $this->_tryEof = 0;
            }
            $this->_lastBufSize = $bufSize;
            $result = strpos($this->_buf, $eofStr);
    
        return $result;
    }
    
    private function _read()
    {
        $this-&gt;_buf = '';
        $endResponse = "&lt;/return&gt;";
        while (!$this-&gt;_feof($endResponse)) {
            $buf = fread($this-&gt;_handler, 10240);
            $this-&gt;_buf .= $buf;
        }
        // ...
    }
    

    }


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2