How to call a WebSocket programmatically (using PHP)?

前端 未结 5 2057
孤街浪徒
孤街浪徒 2021-02-04 18:46

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 sen

5条回答
  •  礼貌的吻别
    2021-02-04 19:29

    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);
    

提交回复
热议问题