Laravel Beyondcode websockets - 如果 verify_peer 为 true 则不起作用

作者:编程家 分类: laravel 时间:2025-09-10

使用 Laravel Beyondcode Websockets 实现实时通信

Laravel Beyondcode Websockets 是一个强大的 Laravel 扩展包,用于实现实时通信。它基于 WebSockets 技术,提供了简单易用的接口和功能,方便开发者构建实时应用程序。

在使用 Laravel Beyondcode Websockets 过程中,我们可能会遇到一个问题:当 `verify_peer` 设置为 `true` 时,SSL 证书验证无法正常工作。在本文中,我们将讨论这个问题,并提供解决方案。

问题描述

当我们在配置 Laravel Beyondcode Websockets 时,可以通过设置 `verify_peer` 参数来控制是否启用 SSL 证书验证。当 `verify_peer` 设置为 `true` 时,WebSockets 连接会尝试验证服务器的 SSL 证书。

然而,一些开发环境中的 SSL 证书可能无法通过验证,导致连接失败。这可能是由于自签名证书、过期证书或其他问题引起的。在这种情况下,我们需要禁用 SSL 证书验证。

解决方案

要解决这个问题,我们可以通过修改 Beyondcode\WebSockets\Server\Connection 类来禁用 SSL 证书验证。我们可以在 `verify_peer` 参数为 `true` 时,手动设置 `verify_peer_name` 和 `allow_self_signed` 参数为 `false`,以避免验证失败。

下面是一个示例代码,演示了如何修改 Connection 类来解决 SSL 证书验证问题:

php

namespace App\WebSocket;

use BeyondCode\WebSockets\Server\Connection as BaseConnection;

class Connection extends BaseConnection

{

protected function createTlsContext(): ?resource

{

$context = parent::createTlsContext();

if ($this->shouldVerifyPeer()) {

stream_context_set_option($context, 'ssl', 'verify_peer_name', false);

stream_context_set_option($context, 'ssl', 'allow_self_signed', false);

}

return $context;

}

protected function shouldVerifyPeer(): bool

{

return $this->config['verify_peer'] ?? false;

}

}

在上面的示例中,我们创建了一个名为 Connection 的自定义类,继承自 Beyondcode\WebSockets\Server\Connection 类。在 createTlsContext 方法中,我们手动设置了 `verify_peer_name` 和 `allow_self_signed` 参数,以避免 SSL 证书验证失败。shouldVerifyPeer 方法用于确定是否应该启用 SSL 证书验证。

使用自定义 Connection 类

为了使用自定义的 Connection 类,我们需要在 Laravel Beyondcode Websockets 的配置文件中指定该类。打开 config/websockets.php 文件,找到 `websocket_handler` 配置项,并将其值设置为我们自定义的 Connection 类名。例如:

php

'websocket_handler' => App\WebSocket\Connection::class,

通过这样的配置,我们的自定义 Connection 类将会代替默认的 Connection 类,并在创建 WebSockets 连接时生效。

本文介绍了在使用 Laravel Beyondcode Websockets 时,当 `verify_peer` 参数为 `true` 时,SSL 证书验证无法正常工作的问题,并提供了解决方案。我们可以通过修改 Beyondcode\WebSockets\Server\Connection 类来禁用 SSL 证书验证,以解决这个问题。通过自定义 Connection 类并在配置文件中指定,我们可以轻松地应用这个解决方案。

希望本文对你在使用 Laravel Beyondcode Websockets 实现实时通信时有所帮助!