How to call a WebSocket programmatically (using PHP)?

Nightwolf picture Nightwolf · Apr 19, 2011 · Viewed 15.1k times · Source

I have a situation where I need to update one browser window based on input from the other. Right now I'm using WebSockets and it's working great.

Now I want to send data to the WebSocket using PHP instead of the browser (so instead of ws://, use PHP code). In other words, I want to simulate the WebSocket.send() call using PHP instead of JavaScript.

I have the following code which doesn't seem to work (the onmessage is not being called):

if ( 
        function_exists('socket_create') AND
        $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) AND
        $sock_data = socket_connect($sock, "127.0.0.1", 12345)
    ) {  
        $msg = "hello world";
        $sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set 
        $sock_data = socket_write($sock, $msg, strlen($msg)); //Send data
        socket_close($sock); //Close socket
    } 

Answer

Nightwolf picture Nightwolf · Apr 19, 2011

Here's how it's done:

http://permalink.gmane.org/gmane.comp.lang.javascript.nodejs/18088

$host = 'localhost';  //where is the websocket server
$port = 9000;
$local = "http://localhost/";  //url where this script run
$data = 'hello world!';  //data to be send

$head = "GET / HTTP/1.1"."\r\n".
            "Upgrade: WebSocket"."\r\n".
            "Connection: Upgrade"."\r\n".
            "Origin: $local"."\r\n".
            "Host: $host"."\r\n".
            "Content-Length: ".strlen($data)."\r\n"."\r\n";
//WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);  //receives the data included in the websocket package "\x00DATA\xff"
fclose($sock);