Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send data/text from PHP using WebSocket to process?

I have process on server which acts as WebSocket server (not written in Ratchet). I want to be able to send data to this process using PHP (as client).

I found a lot of examples to send as TCP like this:

<?php
  $addr = gethostbyname("localhost");

  $client = stream_socket_client("tcp://$addr:8887", $errno, $errorMessage);

  if ($client === false) {
      throw new UnexpectedValueException("Failed to connect: $errorMessage");
  }

  fwrite($client, "GET / HTTP/1.0\r\nHost: localhost\r\nAccept: */*\r\n\r\n");
  echo stream_get_contents($client);
?>

All I need I to send message to the process and close the connection. The result that I expect is the result from the webSocket will be later printed or "echo" to the PHP page.

Is there a way to make it work with curl in php?

like image 431
Pini Cheyni Avatar asked Jun 02 '16 15:06

Pini Cheyni


1 Answers

I have found this code on github, (I can't find the exact repo where I got it from because I have looked and tried a lot of them)

<?php
class WebsocketClient {

    private $_Socket = null;

    public function __construct($host, $port) {
        $this->_connect($host, $port);
    }

    public function __destruct() {
        $this->_disconnect();
    }

    public function sendData($data) {
        // send actual data:
        fwrite($this->_Socket, "\x00" . $data . "\xff") or die('Error:' . $errno . ':' . $errstr);
        $wsData = fread($this->_Socket, 2000);
        $retData = trim($wsData, "\x00\xff");
        return $retData;
    }

    private function _connect($host, $port) {
        $key1 = $this->_generateRandomString(32);
        $key2 = $this->_generateRandomString(32);
        $key3 = $this->_generateRandomString(8, false, true);

        $header = "GET /echo HTTP/1.1\r\n";
        $header.= "Upgrade: WebSocket\r\n";
        $header.= "Connection: Upgrade\r\n";
        $header.= "Host: " . $host . ":" . $port . "\r\n";
        $header.= "Origin: http://localhost\r\n";
        $header.= "Sec-WebSocket-Key1: " . $key1 . "\r\n";
        $header.= "Sec-WebSocket-Key2: " . $key2 . "\r\n";
        $header.= "\r\n";
        $header.= $key3;


        $this->_Socket = fsockopen($host, $port, $errno, $errstr, 2);
        fwrite($this->_Socket, $header) or die('Error: ' . $errno . ':' . $errstr);
        $response = fread($this->_Socket, 2000);

        /**
         * @todo: check response here. Currently not implemented cause "2 key handshake" is already deprecated.
         * See: http://en.wikipedia.org/wiki/WebSocket#WebSocket_Protocol_Handshake
         */
        return true;
    }

    private function _disconnect() {
        fclose($this->_Socket);
    }

    private function _generateRandomString($length = 10, $addSpaces = true, $addNumbers = true) {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
        $useChars = array();
        // select some random chars:    
        for ($i = 0; $i < $length; $i++) {
            $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
        }
        // add spaces and numbers:
        if ($addSpaces === true) {
            array_push($useChars, ' ', ' ', ' ', ' ', ' ', ' ');
        }
        if ($addNumbers === true) {
            array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
        }
        shuffle($useChars);
        $randomString = trim(implode('', $useChars));
        $randomString = substr($randomString, 0, $length);
        return $randomString;
    }

}

$WebSocketClient = new WebsocketClient('localhost', 8887);
echo $WebSocketClient->sendData("MyUserNameFromPHP");
unset($WebSocketClient);
?>

Out of 7 php websocket clients that I tried, this is the only one that I was able to work with. It doesn't requires any external files or frameworks. This is simple implementation for executing short command that doesn't require persistent connection to webSocket server.

I hope it helps you guys , and you will save some time !!!

like image 62
Pini Cheyni Avatar answered Oct 18 '22 17:10

Pini Cheyni