node.js - send and request form php to nodejs websocket (with ssl self signed)

one text

Summary:

javascript client to nodejs websocket server EVERYTHING OK (connecting, sending and receiving data)

PHP socket_connect() No errors but never connect to nodejs websocket server

PHP stream_socket_client() never connect to nodejs websocket server (Error: HTTP/1.1 400 Bad Request Connection: close)

PHP CURL connect to nodejs websocket but nothing like response curl POST get error Invalid HTTP method and curl GET no errors but nothing like response (both POST and GET i can see them in nodejs server.on('upgrade')


Apache httpd-ssl.conf

RewriteEngine on
RewriteRule /wss/(.*) wss://%{HTTP_HOST}%:1301$1 [P,L]

javascript client (EVERYTING OK connecting, sending and receiving data)

var host = location.host;
var port = 1301;
var wss_path = 'wss';
var wss_host = 'ws://'+host+':'+port+'/'+wss_path;

var socket = new WebSocket(wss_host);

socket.onopen = function(msg) {
    socket.send(JSON.stringify({msg:'Hello from js client'}));
}
socket.onmessage = function(msg) {
    console.log('Received fom server',JSON.parse(msg.data));
};

nodejs websocket server: (EVERYTHING OK with javascript client)

const port = 1301;
const wss_path = 'wss';
const https = require('https');
const fs = require('fs');
const ws = require('ws');

const json_encode = require('json_encode');
const json_decode = function(str){return JSON.parse(str)};

const key_path = 'c:/my/key/path_to/private_key.key';
//self signed certificate
const key_certificate = 'c:/my/cert/path_to/certificate.crt';

const options = {
  key: fs.readFileSync(key_path),
  cert: fs.readFileSync(key_certificate)  
};

const server = https.createServer(options, function(req, res){
    //handle here other requests
}
server.on('upgrade', function upgrade(req, sock, head) {
    console.log('on upgrade',req.headers);
});
server.listen(port, function(){
    console.log('Https running on port ' + port);
});
wss = new ws.Server({server, path: '/'+wss_path});

wss.on('connection', function connection(ws, req) {
    console.log('ON connection',req.headers);
    ws.send(json_encode({msg:'welcome from nodejs'}));
});

PHP common variables:

$host = $_SERVER["HTTP_HOST"];
$port = 1301;
$wss_path = "wss";
$ip = gethostbyname($host);

1st attempt PHP https client socket_connect()

//No errors but never connect to nodejs server $result = true , $response = "";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, $ip, $port);

// Create HTTP request
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: $host\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

// Send HTTP request
socket_write($socket, $in, strlen($in));

// Read and output response
$response = "";
while ($out = socket_read($socket, 2048)){
    $response .= $out;
}

socket_close($socket);
//NO ERRORS BUT NEVER CONNECT TO NODEJS SERVER $result = true , $response = "";
echo json_encode([$result,$response]);

2nd attempt SSL CLIENT SOCKET stream_socket_client() (NEVER CONNECT TO NODEJS SERVER) Error: HTTP/1.1 400 Bad Request Connection: close)

$context = stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);

if ($socket = stream_socket_client(
        'ssl://'.$host.':'.$port.'/'.$path,
        $errno,
        $errstr,
        30,
        STREAM_CLIENT_CONNECT,
        $context)
) {
    fwrite($socket, "hello from PHP\n");
    echo fread($socket,$port);
    fclose($socket);
} else {
   echo "ERROR: $errno - $errstr\n";
}
//(NEVER CONNECT TO NODEJS SERVER) Error: HTTP/1.1 400 Bad Request Connection: close)

3rd attempt PHP curl (The first sign that does something) See comments for details

$data = array("TEST" => "PHP TO NODEJS", "msg" => "HELLO FROM PHP");
$data_string = json_encode($data);

$ch = curl_init("https://$host:$port/$path"); 

//see below explanations about GET and POST attempts                                                                      
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://$host:$port/$path?".http_build_query($data));


curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        "Connection: Upgrade",
        "Upgrade: WebSocket",
        "Host: $host",
        "Origin: https://$host",
        "Sec-WebSocket-Version: 13",
        "Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==",
        "Data-string: ".$data_string
    )                                                                       
);                                                                                                                   

$result = curl_exec($ch);
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);


//    when I use POST (nodejs server -> on upgrade -> show me a new request)
// but I get this:
//$result = Invalid HTTP method
//$errors = ''
//$response = 405

echo json_encode([$result,$errors,$response]);

//    when I USE GET (commenting POST options above) 
//    (nodejs server -> on upgrade -> show me a new request)
// but PHP does not receive anything. It stays like waiting

The final question

  • Is there a way that PHP can send and receive data to and from nodejs websocket server without employing other frameworks? *

Source