PHP Websocket Client - Keep connection open
Since the php script that renders the page finishes execution, you need to implement websockets on the client itself using a js script
<?php
// here output your page
wss_path = 'wss://example.com/?token=xyz123456';
?>
// JS script (see its working results in console by pressing `F12`)
<script>
let socket = new WebSocket(<?= wss_path ?>);
socket.onopen = function(e) {
console.log('[open] Connection opened');
socket.send("Hi! I am a new web-socket client.");
};
socket.onmessage = function(event) {
const message = JSON.parse(event.data);
console.log('From the server:', message);
};
socket.onclose = function(event) {
if (event.wasClean) {
console.log(`[close] Connetion closed clearly, code=${event.code} reason=${event.reason}`);
} else {
console.log('[close] Сonnection closed unexpectedly');
}
};
socket.onerror = function(error) {
console.log(`[error] ${error}`);
};
</script>
Unable to connect Javascript client to PHP server using websockets
I found the answer. I was missing the handshake headers when establishing web socket with Javascript client. Please refer to this question and look for the PHP - Server code on the question; since it is the proper way to create a web socket between Javascript client and PHP server and solved my problem.
Connecting to a ratchet websocket server using PHP
I have tried this project alongside Ratchet, and it works perfectly as a PHP client:
https://github.com/Textalk/websocket-php
Install with:composer require textalk/websocket 1.0.*
And a usage example:
<?php
require('vendor/autoload.php');
use WebSocket\Client;
$client = new Client("ws://127.0.0.1:1234");
$client->send("Hello from PHP");
echo $client->receive() . "\n"; // Should output 'Hello from PHP'
I tested, and this also works with SSL if you're using wss:// (for remote websockets).
Related Topics
How to Capture Search Term from Google Search
JSON: PHP to JavaScript Safe or Not
Php, MySQL - Too Many Connections to Database Error
Jquery Load() and PHP Variables
Sending Bcc Emails Using a Smtp Server
How to Enable Ssl in Wamp Server
PHP Eval and Capturing Errors (As Much as Possible)
Php: Trying to Create a New Line with "\N"
How to Serve an Image with Laravel
How to Eliminate PHP5 Strict Standards Errors
Detect Mobile Devices - and Tablet Devices
How to Get Jquery Code Completion in Netbeans
How to Use SQL Server Connection in Laravel