【问题标题】:Socket.io 3 and PHP integrationSocket.io 3 和 PHP 集成
【发布时间】:2021-04-08 03:49:51
【问题描述】:

我使用 PHP SocketIO 类连接 NodeJS 应用程序并发送消息。 Socket.io 2 一切正常,但升级到版本 3 后 PHP 集成停止工作。

当我发送请求时,我得到了这个响应:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: hNcappwZIQEbMz7ZGWS71lNcROc=

但我在 NodeJS 端看不到任何东西,即使我尝试使用“连接”事件记录与服务器的任何连接。

这是 PHP 类:

class SocketIO
{
    /**
     * @param null $host - $host of socket server
     * @param null $port - port of socket server
     * @param string $action - action to execute in sockt server
     * @param null $data - message to socket server
     * @param string $address - addres of socket.io on socket server
     * @param string $transport - transport type
     * @return bool
     */
    public function send($host = null, $port = null, $action= "message",  $data = null, $address = "/socket.io/?EIO=2", $transport = 'websocket')
    {
        $fd = fsockopen($host, $port, $errno, $errstr);
        
        if (!$fd) {
            return false;
        } //Can't connect tot server
        $key = $this->generateKey();
        $out = "GET $address&transport=$transport HTTP/1.1\r\n";
        $out.= "Host: https://$host:$port\r\n";
        $out.= "Upgrade: WebSocket\r\n";
        $out.= "Connection: Upgrade\r\n";
        $out.= "Sec-WebSocket-Key: $key\r\n";
        $out.= "Sec-WebSocket-Version: 13\r\n";
        $out.= "Origin: https://$host\r\n\r\n";

        fwrite($fd, $out);

        // 101 switching protocols, see if echoes key
        $result= fread($fd,10000);

        preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $result, $matches);

        $keyAccept = trim($matches[1]);
        $expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $handshaked = ($keyAccept === $expectedResonse) ? true : false;

        if ($handshaked){
            fwrite($fd, $this->hybi10Encode('42["' . $action . '", "' . addslashes($data) . '"]'));
            fread($fd,1000000);
            return true;
        } else {return false;}
    }
    private function generateKey($length = 16)
    {
        $c = 0;
        $tmp = '';
        while ($c++ * 16 < $length) { $tmp .= md5(mt_rand(), true); }
        return base64_encode(substr($tmp, 0, $length));
    }
    private function hybi10Encode($payload, $type = 'text', $masked = true)
    {
        $frameHead = array();
        $payloadLength = strlen($payload);
        switch ($type) {
            case 'text':
                $frameHead[0] = 129;
                break;
            case 'close':
                $frameHead[0] = 136;
                break;
            case 'ping':
                $frameHead[0] = 137;
                break;
            case 'pong':
                $frameHead[0] = 138;
                break;
        }
        if ($payloadLength > 65535) {
            $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 255 : 127;
            for ($i = 0; $i < 8; $i++) {
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
            }
            if ($frameHead[2] > 127) {
                $this->close(1004);
                return false;
            }
        } elseif ($payloadLength > 125) {
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
            $frameHead[1] = ($masked === true) ? 254 : 126;
            $frameHead[2] = bindec($payloadLengthBin[0]);
            $frameHead[3] = bindec($payloadLengthBin[1]);
        } else {
            $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
        }
        foreach (array_keys($frameHead) as $i) {
            $frameHead[$i] = chr($frameHead[$i]);
        }
        if ($masked === true) {
            $mask = array();
            for ($i = 0; $i < 4; $i++) {
                $mask[$i] = chr(rand(0, 255));
            }
            $frameHead = array_merge($frameHead, $mask);
        }
        $frame = implode('', $frameHead);
        for ($i = 0; $i < $payloadLength; $i++) {
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
        }
        return $frame;
    }
}

感谢您的帮助!

【问题讨论】:

    标签: php node.js sockets websocket


    【解决方案1】:

    我对 github 上存在的所有库都遇到了同样的问题,问题是它们被放弃或没有更新到 socket.io V3。

    在 socket.io 文档中说:

    TL;DR:由于一些重大更改,v2 客户端将无法连接到 v3 服务器(反之亦然)

    要解决这个问题,你需要了解 socket.io 客户端是如何工作的,这很容易,因为在协议文档中,在 sample-session 部分。

    Socket.Io protocol documentation

    要解决这个问题,你需要忘记 fsockopen 和 fwrite 函数,你需要直接使用 CURL 来执行协议文档中提到的请求。

    请求 n°1
    GET
    url:/socket.io/?EIO=4&transport=polling&t=N8hyd7H
    打开数据包: 打开 php 和 socket.io 服务器之间的连接。服务器将返回一个名为“sid”的“会话 id”,您将把它添加到后续查询的 url 查询中。

    请求 n°2
    POST
    url:/socket.io/?EIO=4&transport=polling&t=N8hyd7H&sid =sessionIdFromRequest1
    post body: '40'
    命名空间连接请求:你需要在 body 中发送数字 40,作为一个字符串,这意味着你想连接到socket.io“消息”类型

    请求 n°3
    GET
    url:/socket.io/?EIO=4&transport=polling&t=N8hyd7H&sid =sessionIdFromRequest1
    命名空间连接批准:如果连接成功或出现错误,这将返回,如果您需要令牌,这里是 socket.io 服务器授权您的连接的时间。 p>

    请求 n°4
    POST
    url:/socket.io/?EIO=4&transport=polling&t=N8hyd7H&sid =sessionIdFromRequest1
    帖子正文:42[事件,数据]
    例如 42["notifications","Hi, Im a notification"] 等价于 socket.emit(event,data) 向服务器发送消息:将您的消息发送到 socket.io 服务器。

    这是一个使用 Symfony 5.2 和 HttpClientInterface 的 BASIC 示例:

    <?php
    
    // install dependencies before: composer require symfony/http-client
    
    use Symfony\Component\HttpClient\CurlHttpClient;
    
    include('vendor/autoload.php');
    
    $client = new CurlHttpClient();
    sendToSocket($client);
    
    function sendToSocket(HttpClientInterface $client)
    {
        $first = $client->request('GET', 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=N8hyd6w');
        $res = ltrim($first->getContent(), '0');
        $res = json_decode($res, true);
        $sid = $res['sid'];
    
        $second = $client->request('POST', 'http://localhost:3000/socket.io/?EIO=4&transport=polling&sid='.$sid, [
                'body' => '40'
            ]);
        $third = $client->request('GET', 'http://localhost:3000/socket.io/?EIO=4&transport=polling&sid='.$sid);
    
        $fourth = $client->request('POST', 'http://localhost:3000/socket.io/?EIO=4&transport=polling&sid='.$sid, [
            'body' => '42["notifications","Hi, Im a notification"]'
        ]);
    
    }
    

    如您所见,这非常简单,而且您不需要麻烦的“复制粘贴”库。我说“复制粘贴”是因为都使用相同的代码打开de socket并发送信息,但没有一个与socket.io V3兼容。

    这是一张图片,证明给定的代码在 2021 年 1 月 4 日使用 php 7.4、symfony 5.2 和 socket.io V3。

    这是我在节点中的测试服务器

    // Install dependencies before: npm i express socket.io
    
    const app = require('express')();
    const http = require('http').createServer(app);
    
    const io = require('socket.io')(http, {
       cors: {
          origin: "*",
          methods: ["GET", "POST"]
       }
    });
    
    io.on('connection', function (socket) {
    
       console.log("New Connection with transport", socket.conn.transport.name);
    
       socket.on('notifications', function (data) {
          console.log(data);
       });
    });
    
    http.listen(3000, () => {
       console.log('Server started port 3000');
    });
    

    我需要说的是,如果您想向您的 socket.io 服务器发送“单向”消息(例如新通知或任何不需要永久连接的消息),那么这个解决方案非常有效,只是“一枪”没有别的。

    来自墨西哥的快乐编码和问候。

    这是另一个例子:

    第一列是 Postman 向 php 服务器发出请求,模拟服务器端事件,就像创建了一个新问题。在响应中是您需要发出的 4 个请求的响应正文的转储。

    第二列是socket.IO节点服务器运行在3000端口

    最后一列是 chrome 控制台,模拟用户通过 websocket 连接到 socket.IO 服务器,在 'questions' 事件中寻找通知。

    【讨论】:

      猜你喜欢
      • 2016-12-29
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2023-03-30
      • 2022-01-10
      • 2017-01-30
      相关资源
      最近更新 更多