如何使用WebSocket从PHP发送数据/文本进行处理?

Pin*_*yni 4 php browser sockets websocket

我在服务器上有进程,它充当WebSocket服务器(不是用Ratchet编写的).我希望能够使用PHP(作为客户端)将数据发送到此进程.

我找到了很多像TCP一样发送的例子:

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

我只需要向进程发送消息并关闭连接.我期望的结果是webSocket的结果将在以后打印或"回显"到PHP页面.

有没有办法让它在php中使用curl

Pin*_*yni 11

我在github上找到了这个代码,(我无法找到我从中得到它的确切仓库,因为我看了很多并尝试了很多)

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

在我尝试的7个php websocket客户端中,这是我能够使用的唯一一个.它不需要任何外部文件或框架.这是执行短命令的简单实现,不需要与webSocket服务器的持久连接.

我希望它可以帮助你们,你们会节省一些时间!

  • 上面提供的代码位于https://github.com/edtsz/PHP-WebSocket/blob/master/client.php (2认同)
  • @pini-cheyni 我无法使用 `sendData` 函数发送数据。我的 Django 套接字服务器上没有显示任何响应。谁能帮我吗? (2认同)