Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a WebSocket programmatically (using PHP)?

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
    } 
like image 571
Nightwolf Avatar asked Apr 19 '11 00:04

Nightwolf


People also ask

Can I use WebSockets with PHP?

Socket as the generator source The thing is, PHP has everything it needs to work with WebSockets.

How do you call a WebSocket?

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

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);
like image 110
Nightwolf Avatar answered Oct 24 '22 05:10

Nightwolf