I am trying to use websocket for replacing constants ajax request to the server, that updates ajax information.
As far as I know in the client-server scenario I should launch a php websocket server from command line:
php -q myserver.php
WHat I am trying to obtain is to lauch the server when I client connects for the first time, and use this server for all the other clients, without using the command line:
var socket = new WebSocket("ws://localhost:10000/myserver.php");
This command I want to run the server if it is not running and open a connection for this client.
Is this possible?
To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://javascript.info"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.
Create the HTTP Server Open the file app. php and add the following code: <? php use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; use MyApp\Socket; require dirname( __FILE__ ) .
You can use and deploy a WebSocket server in a PHP server today.
In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server. The URL to which to connect; this should be the URL to which the WebSocket server will respond.
Yes it is possible but you should look at phpwebsocket
var host = "ws://localhost:10000/myserver.php";
try{
socket = new WebSocket(host);
log('WebSocket - status '+socket.readyState);
socket.onopen = function(msg){ log("Welcome - status "+this.readyState); };
socket.onmessage = function(msg){ log("Received: "+msg.data); };
socket.onclose = function(msg){ log("Disconnected - status "+this.readyState); };
}
catch(ex){ log(ex); }
Server Side that you run php -q myserver.php
log("Handshaking...");
list($resource,$host,$origin) = getheaders($buffer);
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: WebSocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: " . $origin . "\r\n" .
"WebSocket-Location: ws://" . $host . $resource . "\r\n" .
"\r\n";
$handshake = true;
socket_write($socket,$upgrade.chr(0),strlen($upgrade.chr(0)));
phpwebsocket does not support RFC-6455
by default so you can also look at the following
https://github.com/ghedipunk/PHP-Websockets
https://github.com/sebcode/php-websocketserver
https://github.com/Martijnc/phpwebsockets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With