Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start a websocket server in php from the first client request

Tags:

php

websocket

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?

like image 613
albanx Avatar asked Oct 15 '12 11:10

albanx


People also ask

How do I start a WebSocket server?

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.

How configure WebSocket in PHP?

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__ ) .

Can PHP use WebSockets?

You can use and deploy a WebSocket server in a PHP server today.

How do WebSockets connect to clients?

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.


1 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

  • https://github.com/ghedipunk/PHP-Websockets

  • https://github.com/sebcode/php-websocketserver

  • https://github.com/Martijnc/phpwebsockets

like image 54
Baba Avatar answered Sep 30 '22 17:09

Baba