Home » Php » start a websocket server in php from the first client request

start a websocket server in php from the first client request

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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