Summary:
javascript client to nodejs websocket serverEVERYTHING OK
(connecting, sending and receiving data)
PHPsocket_connect()
No errors but never connect to nodejs websocket server
PHPstream_socket_client()
never connect to nodejs websocket server (Error: HTTP/1.1 400 Bad Request Connection: close)
PHPCURL
connect to nodejs websocket but nothing like responsecurl POST
get errorInvalid HTTP method
andcurl GET
no errors but nothing like response (bothPOST
andGET
i can see them in nodejsserver.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 clientsocket_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 SOCKETstream_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 PHPcurl
(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
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
Node.js is an open source server-side framework built on top of the Google Chrome JavaScript Engine. The number of sites using NodeJS has increased by 84,000. It is one of the busiest cross-platform JavaScript runtimes. Node.js is an asynchronous, single-threaded, non-blocking I / O model that makes it lightweight and efficient. The Node.js package ecosystem, npm, is also the world's largest open source library ecosystem.
https://nodejs.org/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.