Swoole ソース コードで Websocket 接続の問題をクエリする方法を学習します

coldplay.xixi
リリース: 2020-11-17 17:01:29
転載
3008 人が閲覧しました

Swoole 教程 ウェブソケットの接続の問題をどのように評価するか。 ##我们目的の Websocket サーバー使用の Swoole は、最近、ベータ版環境を構築する際に WebSocket の変換承認が成功しましたが、一定時間の遅延が発生し、ハートビート、データも送信されませんでした。

Swoole ソース コードで Websocket 接続の問題をクエリする方法を学習します

配置の問題

# Swoole の実験を容易にするために、以下のテストはローカル環境で実行されます。

查看 PHP 日志

在 PHP 日志里,発行一条错误日志:

ErrorException: Swoole\WebSocket\Server::push(): connection[47] の接続されたクライアントは WebSocket ではありませんクライアントまたはクローズ済み
、Websocket 接続が終了していることを示します。ポートは 1215 で、tcpdump -nni lo0 -X port 1215

を介して確認できます。Swoole は协议升级の响应报文を発行した後、Fin 文節、つまり Swoole 主活動切断接続を発行しました。そのため、WebSocket の接続が成功したことを示すブラウザーが表示される可能性がありますが、その後も定期的に問題が発生します。しかし、それはどの時点で切断されているのでしょうか、それとも何を切断するのでしょうか? 我々はソース コードから詳しく調べています。時間がかなり短いため、ハンドシェイク段階で問題が発生していることがわかります。これは

swoole_websocket_handshake()

の近くにあります。
// // swoole_websocket_server.cc
int swoole_websocket_onHandshake(swServer *serv, swListenPort *port, http_context *ctx)
{
    int fd = ctx->fd;
    bool success = swoole_websocket_handshake(ctx);
    if (success)
    {
        swoole_websocket_onOpen(serv, ctx);
    }
    else
    {
        serv->close(serv, fd, 1);
    }
    if (!ctx->end)
    {
        swoole_http_context_free(ctx);
    }
    return SW_OK;
}复制代码
ログイン後にコピー

追踪进 swoole_websocket_handshake() 里,前面部分都是设置响应的 header,响应报文则是在 swoole_http_response_end() 里发出的,它的结果也就是 swoole_websocket_handshake 的结果。

// swoole_websocket_server.cc
bool swoole_websocket_handshake(http_context *ctx)
{
    ...

    swoole_http_response_set_header(ctx, ZEND_STRL("Upgrade"), ZEND_STRL("websocket"), false);
    swoole_http_response_set_header(ctx, ZEND_STRL("Connection"), ZEND_STRL("Upgrade"), false);
    swoole_http_response_set_header(ctx, ZEND_STRL("Sec-WebSocket-Accept"), sec_buf, sec_len, false);
    swoole_http_response_set_header(ctx, ZEND_STRL("Sec-WebSocket-Version"), ZEND_STRL(SW_WEBSOCKET_VERSION), false);

        ...

    ctx->response.status = 101;
    ctx->upgrade = 1;

    zval retval;
    swoole_http_response_end(ctx, nullptr, &retval);
    return Z_TYPE(retval) == IS_TRUE;
}复制代码
ログイン後にコピー

swoole_http_response_end() 代码中我们发现,如果 ctx->keepalive 为 0 的话则关闭连接,断点调试下发现还真就是 0。至此,连接断开的地方我们就找到了,下面我们就看下什么情况下 ctx->keepalive 设置为 1。

// swoole_http_response.cc
void swoole_http_response_end(http_context *ctx, zval *zdata, zval *return_value)
{
    if (ctx->chunk) {
       ...
    } else {
        ...

            if (!ctx->send(ctx, swoole_http_buffer->str, swoole_http_buffer->length))
        {
            ctx->send_header = 0;
            RETURN_FALSE;
        } 
    }

    if (ctx->upgrade && !ctx->co_socket) {
        swServer *serv = (swServer*) ctx->private_data;
        swConnection *conn = swWorker_get_connection(serv, ctx->fd);

        // 此时websocket_statue 已经是WEBSOCKET_STATUS_ACTIVE,不会走进这步逻辑
        if (conn && conn->websocket_status == WEBSOCKET_STATUS_HANDSHAKE) {
            if (ctx->response.status == 101) {
                conn->websocket_status = WEBSOCKET_STATUS_ACTIVE;
            } else {
                /* connection should be closed when handshake failed */
                conn->websocket_status = WEBSOCKET_STATUS_NONE;
                ctx->keepalive = 0;
            }
        }
    }

    if (!ctx->keepalive) {
        ctx->close(ctx);
    }
    ctx->end = 1;
    RETURN_TRUE;
}复制代码
ログイン後にコピー

最终我们找到 ctx->keepalive 是在 swoole_http_should_keep_alive() 里设置的。从代码我们知道,当 HTTP 协议是 1.1 版本时,keepalive 取决于 header 没有设置 Connection: close;当为 1.0 版本时,header 需设置 Connection: keep-alive

Websocket 协议规定,请求 header 里的 Connection 需设置为 Upgrade,所以我们需要改用 HTTP/1.1 协议。

int swoole_http_should_keep_alive (swoole_http_parser *parser)
{
  if (parser->http_major > 0 && parser->http_minor > 0) {
    /* HTTP/1.1 */
    if (parser->flags & F_CONNECTION_CLOSE) {
      return 0;
    } else {
      return 1;
    }
  } else {
    /* HTTP/1.0 or earlier */
    if (parser->flags & F_CONNECTION_KEEP_ALIVE) {
      return 1;
    } else {
      return 0;
    }
  }
}复制代码
ログイン後にコピー

解决问题

从上面的结论我们可以知道,问题的关键点在于请求头的 Connection 和 HTTP 协议版本。

后来问了下运维,生产环境的 LB 会在转发请求时,会将 HTTP 协议版本修改为 1.1,这也是为什么只有 beta 环境存在这个问题,nginx 的 access_log 也印证了这一点。

那么解决这个问题就很简单了,就是手动升级下 HTTP 协议的版本,完整的 nginx 配置如下。

upstream service {
    server 127.0.0.1:1215;
}

server {
    listen 80;
    server_name dev-service.ts.com;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_http_version 1.1;

        proxy_pass http://service;
    }
}复制代码
ログイン後にコピー

重启 Nginx 后,Websocket 终于正常了~

以上がSwoole ソース コードで Websocket 接続の問題をクエリする方法を学習しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:juejin.im
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!