I am currently working on this project (php) where I have to connect my php backend to a remote server using sockets. I am using this code to create the connection and it works fine:
$key=base64_encode(openssl_random_pseudo_bytes(16));
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Pragma: no-cache"."\r\n".
"Accept-Encoding: gzip, deflate"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: http://$host"."\r\n".
"Host: $host"."\r\n".
"Sec-WebSocket-Version: 13"."\r\n".
"Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits"."\r\n".
"Sec-WebSocket-Protocol: b_xmlproc"."\r\n".
"Cache-Control: no-cache"."\r\n".
"Sec-WebSocket-Key: $key"."\r\n".
"Content-Length: 0\r\n"."\r\n";
$sock = pfsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
I trigger this code through an HTTP call and I am trying to avoid creating multiple sockets. For the moment, every time I am triggering this endpoint, a new socket is created. However, I would like to use pre-existing socket if one has been created already instead of a new one. Here is what I tried so far, without success.
- I tried using global variables
$GLOBALS = array('globalsocket' => null);
but the variable is re-created every time a new request is triggered. - I created a file where I tried to serialize the socket and unserialize it, but it did not work; the unserialize socket was of no use
- I tried class variable, but it was recreated each time of course
- I read the documentation but almost all the methods need the instance of the socket in the first place, which is what I am trying to retrieve...
- I also had a look at apc but it's not enabled on the server (and I cannot change that)
If anyone has a clue on how to do that, I would much appreciate ! Thanks.
PS: I must note that I am used to nodejs and not php, which may be the reason why I am having a hard time figuring it out
PPS: I don't have any database where I can store it
Here is how I would do what I want i nodejs
var net = require("net");
const http = require("http");
let client = new net.Socket();
let connected = false;
const requestListener = function (req, res) {
console.log("status", client.listening);
if (!connected) {
client.connect("port", "ip", function () {
console.log("Connected");
connected = true;
});
}
res.writeHead(200);
res.end("Hello, World!");
};
const server = http.createServer(requestListener);
client.on("data", function (data) {
console.log("Received: " + data);
client.destroy(); // kill client after server's response
});
client.on("close", function () {
connected = false;
console.log("Connection closed");
});
client.on("end", function(){
console.log("Connection end");
connected = false;
client.destroy()
})
client.on('error', function(){
console.log("Connection end");
connected = false;
client.destroy()
})
server.listen("xxx");