romainrg/ratchet_client 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

romainrg/ratchet_client

Composer 安装命令:

composer require romainrg/ratchet_client

包简介

CodeIgniter library who allow you to make powerfull applications with realtime interactions by using Websocket technology

README 文档

README

CodeIgniter library who allow you to make powerfull applications with realtime interactions by using Websocket technology and Ratchetphp (Socketo.me) 🚀🚀

📚 Dependencies

  • PHP 5.6+
  • CodeIgniter Framework (3.1.8+ recommanded)
  • Composer
  • PHP Socket extension enabled

🔰 Installation

➡️ Step 1 : Library installation by Composer

Just by running following command in the folder of your project :

composer require romainrg/ratchet_client

Or by adding following lines to your composer.json file :

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

Don't forget to include your autoload to CI config file :

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

➡️ Step 2 : Create library config file in your project (Optional)

You have to create in your CI config folder located in ./application/config/ratchet_client.php or the library will take his own config file based on host 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
);

➡️ Step 3 : Loading the library

You can add the following lines direclty in your Controller file or your MY_Controller global file

$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');

You'r almost done ✔️

Examples of use

➡️ Create your first App

It's not very difficult, the library will do your job and much more !

  • Edit your CI controller Welcome.php with the following lines (this will be our server)
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();
    }
}
  • Create CI controller User.php and add following lines
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));
    }
}
  • Edit your CI view welcome_message.php with following lines (again 😜)
<?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.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    var conn = new WebSocket('ws://localhost: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>

Ok you just created your first app ! ✔️ (easy with CTRL+C and CTRL+V)

➡️ Run the Websocket server

If you wan't to check you'r work, you have to run the server. Open you'r command prompt then type the command bellow in you'r project folder :

php index.php welcome index

If you see the message the message bellow, you are done (don't close your cmd) !

First_launch.png

➡️ Test the App

Open three pages of your project on following url with different IDs : http://localhost/myproject/user/index/204 http://localhost/myproject/user/index/402 http://localhost/myproject/user/index/604

❗ In my example, recipient_id is defined by user_id, as you can see, it's the auth callback who defines recipient ids.

If you have something like that, everything is ok for you:

User_204

You can try is by typing and sending something in each page (see cmd for more logs).

Cmd_list.png

Broadcast messages with your php App 💥 !

If you want to broadcast message with php script or something else you can use library like textalk/websocket (who is included in my composer.json as required library)

Note : The first message is mandatory and always here to perform authentication

$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!')));

Authentication & callbacks ♻️

The library allow you to define some callbacks, here's an example :

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;
    }
}
  • Auth type callback is called at first message posted from client.
  • Event type callback is called on every message posted.

What about Docker 🐳 ?

Easy to start with this command (php 7.1 used)

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"

Bugs 🐛 or feature 💪

Be free to open an issue or send pull request

To do 🚧

  • Origin check
  • WSS support
  • Add app routing fonctionnality
  • Websocket native library

For more CodeIgniter libraries, give me a 🍺😁

> Beer road

🔒 License

GNU General Public License v3.0

romainrg/ratchet_client 适用场景与选型建议

romainrg/ratchet_client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.87k 次下载、GitHub Stars 达 38, 最近一次更新时间为 2018 年 10 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「websocket」 「codeigniter」 「realtime」 「PHP7」 「php-library」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 romainrg/ratchet_client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 romainrg/ratchet_client 我们能提供哪些服务?
定制开发 / 二次开发

基于 romainrg/ratchet_client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.87k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 39
  • 点击次数: 14
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 38
  • Watchers: 4
  • Forks: 23
  • 开发语言: PHP

其他信息

  • 授权协议: GPL-3.0-or-later
  • 更新时间: 2018-10-24