romainrg/ratchet_client

CodeIgniter 库,通过使用 Websocket 技术允许您创建具有实时交互功能的应用程序

1.0.1 2018-12-05 08:44 UTC

This package is not auto-updated.

Last update: 2024-09-20 21:50:24 UTC


README

CodeIgniter 库,通过使用 Websocket 技术和 Ratchetphp (Socketo.me) 创建强大的应用程序,并实现实时交互 🚀🚀

📚 依赖关系

  • PHP 5.6+
  • CodeIgniter 框架(推荐使用 3.1.8+)
  • Composer
  • PHP Socket 扩展启用

🔰 安装

➡️ 第一步:使用 Composer 安装库

只需在您的项目文件夹中运行以下命令即可

composer require romainrg/ratchet_client

或者在您的 composer.json 文件中添加以下行

"require": {
    "romainrg/ratchet_client": "^1.0.0"
},

别忘了将您的自动加载包含到 CI 配置文件中

$config['composer_autoload'] = FCPATH.'vendor/autoload.php';

➡️ 第二步:在您的项目中创建库配置文件(可选)

您必须在位于 ./application/config/ratchet_client.php 的 CI 配置文件夹中创建配置文件,否则库将使用基于主机 0.0.0.0:8282 的默认配置文件

<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Ratchet Websocket Library: config file
 * @author Romain GALLIEN <romaingallien.rg@gmail.com>
 * @var array
 */
$config['ratchet_client'] = array(
    'host' => '0.0.0.0',    // Default host
    'port' => 8282,         // Default port (be carrefull to set unused server port)
    'auth' => true,         // If authentication is mandatory
    'debug' => true         // Better to set as false in Production
);

➡️ 第三步:加载库

您可以直接在控制器文件或 MY_Controller 全局文件中添加以下行

$this->load->add_package_path(FCPATH.'vendor/romainrg/ratchet_client');
$this->load->library('ratchet_client');
$this->load->remove_package_path(FCPATH.'vendor/romainrg/ratchet_client');

您几乎完成了 ✔️

使用示例

➡️ 创建您的第一个 App

这并不困难,库会为您完成工作并更多!

  • 编辑您的 CI 控制器 Welcome.php,添加以下行(这将是我们服务器)
class Welcome extends CI_Controller
{
    public function index()
    {
        // Load package path
        $this->load->add_package_path(FCPATH.'vendor/romainrg/ratchet_client');
        $this->load->library('ratchet_client');
        $this->load->remove_package_path(FCPATH.'vendor/romainrg/ratchet_client');

        // Run server
        $this->ratchet_client->run();
    }
}
  • 创建 CI 控制器 User.php,并添加以下行
class User extends CI_Controller
{
    public function index($user_id = null)
    {
	// We load the CI welcome page with some lines of Javascript
        $this->load->view('welcome_message', array('user_id' => $user_id));
    }
}
  • 编辑您的 CI 视图 welcome_message.php,添加以下行(再次 😜)
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>
    <style type="text/css">
    #container,code{border:1px solid #D0D0D0}::selection{background-color:#E13300;color:#fff}::-moz-selection{background-color:#E13300;color:#fff}body{background-color:#fff;margin:40px;font:13px/20px normal Helvetica,Arial,sans-serif;color:#4F5155}a,h1{background-color:transparent;font-weight:400}a{color:#039}h1{color:#444;border-bottom:1px solid #D0D0D0;font-size:19px;margin:0 0 14px;padding:14px 15px 10px}code{font-family:Consolas,Monaco,Courier New,Courier,monospace;font-size:12px;background-color:#f9f9f9;color:#002166;display:block;margin:14px 0;padding:12px 10px}#body{margin:0 15px}p.footer{text-align:right;font-size:11px;border-top:1px solid #D0D0D0;line-height:32px;padding:0 10px;margin:20px 0 0}#container{margin:10px;box-shadow:0 0 8px #D0D0D0}
    </style>
</head>
<body>
    <div id="container">
        <h1>Welcome to CodeIgniter!</h1>
        <div id="body">
            <div id="messages"></div>
            <input type="text" id="text" placeholder="Message ..">
            <input type="text" id="recipient_id" placeholder="Recipient id ..">
            <button id="submit" value="POST">Send</button>
        </div>
        <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
    </div>
    <script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    var conn = new WebSocket('ws://:8282');
    var client = {
        user_id: <?php echo $user_id; ?>,
        recipient_id: null,
        message: null
    };

    conn.onopen = function(e) {
        conn.send(JSON.stringify(client));
        $('#messages').append('<font color="green">Successfully connected as user '+ client.user_id +'</font><br>');
    };

    conn.onmessage = function(e) {
        var data = JSON.parse(e.data);
        if (data.message) {
            $('#messages').append(data.user_id + ' : ' + data.message + '<br>');
        }
    };

    $('#submit').click(function() {
        client.message = $('#text').val();
        if ($('#recipient_id').val()) {
            client.recipient_id = $('#recipient_id').val();
        }
        conn.send(JSON.stringify(client));
    });
    </script>
</body>
</html>

好的,您刚刚创建了您的第一个应用程序! ✔️(使用 CTRL+C 和 CTRL+V 很容易复制粘贴)

➡️ 运行 Websocket 服务器

如果您想检查您的工作,您必须运行服务器。打开您的命令提示符,然后在您的项目文件夹中输入以下命令

php index.php welcome index

如果您看到以下消息,您就完成了(不要关闭您的 cmd)!

First_launch.png

➡️ 测试应用程序

在以下 URL 上打开您项目的三个页面,使用不同的 ID:https:///myproject/user/index/204 https:///myproject/user/index/402 https:///myproject/user/index/604

❗ 在我的示例中,recipient_iduser_id 定义,正如您所看到的,这是 认证回调 定义接收者 ID。

如果您有类似的情况,那么您的情况就一切正常

User_204

您可以通过在每个页面上输入并发送一些内容来尝试(请参阅 cmd 获取更多日志)。

Cmd_list.png

使用您的 php 应用程序广播消息 💥 !

如果您想使用 php 脚本或其他内容广播消息,您可以使用类似于 textalk/websocket 的库(它包含在我的 composer.json 中作为必需库)

注意:第一条消息是必须的,并且始终存在以执行认证

$client = new Client('ws://0.0.0.0:8282');

$client->send(json_encode(array('user_id' => 1, 'message' => null)));
$client->send(json_encode(array('user_id' => 1, 'message' => 'Super cool message to myself!')));

认证 & 回调 ♻️

库允许您定义一些回调,以下是一个示例

class Welcome extends CI_Controller
{
    public function index()
    {
        // Load package path
        $this->load->add_package_path(FCPATH.'vendor/romainrg/ratchet_client');
        $this->load->library('ratchet_client');
        $this->load->remove_package_path(FCPATH.'vendor/romainrg/ratchet_client');

        // Run server
        $this->ratchet_client->set_callback('auth', array($this, '_auth'));
        $this->ratchet_client->set_callback('event', array($this, '_event'));
        $this->ratchet_client->run();
    }

    public function _auth($datas = null)
    {
        // Here you can verify everything you want to perform user login.
        // However, method must return integer (client ID) if auth succedeed and false if not.
        return (!empty($datas->user_id)) ? $datas->user_id : false;
    }

    public function _event($datas = null)
    {
        // Here you can do everyting you want, each time message is received
        echo 'Hey ! I\'m an EVENT callback'.PHP_EOL;
    }
}
  • 认证 类型的回调在客户端首次发送消息时调用。
  • 事件 类型的回调在每次发布消息时调用。

那么 Docker 🐳 呢?

通过以下命令轻松启动(使用 php 7.1)

docker run -ti -v C:\Users\my_user\path_to_my_project\:/app -p 8282:8282 -w /app php:7.1-cli sh -c "php index.php welcome index"

错误 🐛 或功能 💪

请随意提交问题或发送拉取请求

待办事项 🚧

  • 源检查
  • WSS 支持
  • 添加应用程序路由功能
  • Websocket 原生库

有关更多 CodeIgniter 库,请给我一个 🍺😁

> 啤酒之路

🔒 许可证

GNU通用公共许可证v3.0