How to use only one socket to send many HTTP requests in PHP?

I have a PHP class for a push message with a socket like:

function __construct()
{
     $this->socket = fsockopen($this->host, $this->port, $errno, $errstr, 0); //I tried with 99999 for timeout too
}

function push($params)
{
     $req = 'GET /push?'.$params." HTTP/1.1\r\n"
            . 'Host: '.$this->host."\r\n"
            . "Content-Type: application/x-www-form-urlencoded\r\n"
            . 'Content-Length: '.strlen($params)."\r\n"
            . "Connection: keep-alive\r\n\r\n";

     fwrite($this->socket, $req);
}

But if I tried to push 2 or more posts, only one gets NodeJS serveur:

foreach(['foo=2', 'bar=42'] as $loop)
{
   $pusher->push($loop);
}

Now, if I put this line $this->socket = fsockopen($this->host, $this->port, $errno, $errstr, 0);immediately before fwrite, all messages will be sent ...

So why can't I use only one connection for multiple requests with the same socket?

I use "keep-alive" and I do not call fclose, so I do not understand why my nodeJS server receives only one message in the first case ...

0
source share

All Articles