I've got a node websockets server all set up with a chat service working great. But I want a LAMP server to be able to send periodic messages to users connected to the websocket server. (Either in response to user browser actions or cron jobs). So I needed some PHP code for sending a request to the node server (both on Google Compute Engine).
I found via this answer: https://stackoverflow.com/a/22411059/947374 ...a link to a forum where someone got this pretty well worked out: https://forum.ripple.com/viewtopic.php?f=2&t=6171&p=43313#p43313
My PHP code now looks like:
//local address of node server
$host='XXX.XXX.XXX.XXX';
$port=80;
//location where THIS script is running FROM
$local="http://localhost";
//json the data to send
$data=json_encode($data);
//some very particular headers
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: $local"."\r\n".
"Host: $host"."\r\n".
"Sec-WebSocket-Version: 13"."\r\n".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
//WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
//see the second link above for what hybi10Encode() is doing
fwrite($sock, hybi10Encode($data)) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);
The data gets sent from PHP to node. Beautiful. Praise the Lord.
Only problem is the connection appears to stay open for about 60 seconds. The data gets sent from PHP to node immediately, the webchat responds right away like I want it to. But the browser tab requesting the PHP script spins for those 60 seconds and won't take another request until the first has finished.
I had thought the inclusion of fclose() would make it so the connection doesn't stay open like this.
I also tried changing the headers to: Connection: Close AND/OR tried GET / HTTP/1.0 (As per some advice of other threads with similar issues) This didn't help either.
Any advice on how I can get the PHP script to close the connection immediately or have the node server drop the connection from the LAMP server as soon as it's done processing its request?