search
HomePHP FrameworkThinkPHPTP5 integrates WorkerMan and GatewayWorker

TP5 integrates GatewayWorker

Windows version installation

a) Use composer create-project topthink/think testTG to install thinkphp5.

b) Enter the directory of thinkphp5, here is testTG, and use composer require workerman/gateway-worker-for-win to install the Windows version of gateway.

c) Go to the official website to download the Windows version of gateway-worker, which contains a demo. http://www.workerman.net/download

d) Unzip the downloaded compressed package and copy all the files in Applications/Yourapp to any folder in the thinkphp5 directory application, here named push .

e) Copy start_for_win.bat in the decompressed folder to the root directory of thinkphp5, which is the directory at the same level as application.

f) Right-click start_for_win.bat, click Edit, change the directory inside to your own directory, here it is changed to

php application\push\start_register.php application\push\start_gateway.php application\push\start_businessworker.php
Pause

g) Save and exit. Double click to run.

Linux version installation

a) Use composer create-project topthink/think testTG to install thinkphp5.

b) Enter the directory of thinkphp5, Here is testTG. Use composer require workerman/gateway-worker to install the Linux version of gateway.

c) Go to the official website to download the Linux version of gateway-worker, which contains a demo. http://www.workerman.net/download

d) Unzip the downloaded compressed package and copy all the files in Applications/Yourapp to any folder in the thinkphp5 directory application, here named push .

e) Copy start.php in the decompressed folder to the root directory of thinkphp5, which is a directory at the same level as application.

f) Change the path in the forearch loop brackets in the last part of the start.php file to your correct path.

Start on the command line php start.php start.

TP5 integrationWrokerMan

Windows version installation

a) Use composer create-project topthink /think testTW to install thinkphp5.

b) Enter the thinkphp5 root directory, which is testTW. First use composer require topthink/think-worker,

and then use composer require workerman/workerman-for-win to install workererman. After successful installation, delete vendor\workerman\workerman.

c) Create server.php in the thinkphp5 root directory (that is, the directory at the same level as application) and edit the content.

<?php
efine(&#39;APP_PATH&#39;, __DIR__ . &#39;/application/&#39;);
define(&#39;BIND_MODULE&#39;,&#39;push/Worker&#39;);
// 加载框架引导文件
require __DIR__ . &#39;/thinkphp/start.php&#39;;

d) Create workerman’s controller and name it Worker.php. In application/push/controller, the directory does not exist and is created by itself. Add the following content:

protected $socket = 'websocket://127.0.0.1:2346' where 127.0.0.1 is the IP address of the socket server. Listen here to port 2346 of this machine.

<?php
 
namespace app\push\controller;
 
use think\worker\Server;
 
class Worker extends Server
{
    protected $socket = &#39;websocket://127.0.0.1:2346&#39;;
 
    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        $connection->send(&#39;我收到你的信息了&#39;);
    }
 
    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
 
    }
 
    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        
    }
    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }
 
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
 
    }
}

e) Run from the command line and start the listening service php server.php

f) Create a new html file at any location. The content is:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
    alert("连接成功");
    ws.send(&#39;tom&#39;);
    alert("给服务端发送一个字符串:tom");
};
ws.onmessage = function(e) {
    alert("收到服务端的消息:" + e.data);
};
</script>

g) Save it and open it with a browser, you can see that the link is successful.

Linux version installation

a) Just execute the composer command in step b) of Windows version installation: composer require topthink/think-worker. That’s it, the rest of the steps remain unchanged.

Simple use of GatewayWorker

<script type="text/javascript">
/**
 * 与GatewayWorker建立websocket连接,域名和端口改为你实际的域名端口,
 * 其中端口为Gateway端口,即start_gateway.php指定的端口。
 * start_gateway.php 中需要指定websocket协议,像这样
 * $gateway = new Gateway(websocket://0.0.0.0:7272);
 */
ws = new WebSocket("ws://127.0.0.1:8282");
// 服务端主动推送消息时会触发这里的onmessage
ws.onmessage = function(e){
    // json数据转换成js对象
    var bindUrl = "{:url(&#39;push/BindClientId&#39;)}";
    var data = e.data;
 
    var type = data.type || &#39;&#39;;
    switch(type){
        // Events.php中返回的init类型的消息,将client_id发给后台进行uid绑定
        case &#39;init&#39;:
            // 利用jquery发起ajax请求,将client_id发给后端进行uid绑定
            $.post(bindUrl, {client_id: data.client_id}, function(data){
 
            }, &#39;json&#39;);
            break;
        // 当mvc框架调用GatewayClient发消息时直接alert出来
        default :
        var text = e.data;
            var str = &#39;<li style="width:100%; height:60px; border:1px solid #000">&#39; +text +&#39;</li>&#39;;
            $(&#39;#message_box&#39;).append();
           // alert(e.data);
    }
};
</script>
class Push{
   
    public function helloAction () {
        $uid = $_GET[&#39;uid&#39;];
        session(&#39;uid&#39;, $uid);
 
        $view = new View;
        return $view->fetch();
    }
 
    public function BindClientIdAction () {
        
        $client_id = $_POST[&#39;client_id&#39;];
        // 设置GatewayWorker服务的Register服务ip和端口,请根据实际情况改成实际值
        Gateway::$registerAddress = &#39;127.0.0.1:1238&#39;;
 
        $bindUid = session(&#39;uid&#39;);
        // 假设用户已经登录,用户uid和群组id在session中
        // client_id与uid绑定
        Gateway::bindUid($client_id, $bindUid);
        // 加入某个群组(可调用多次加入多个群组)
        // Gateway::joinGroup($client_id, $group_id);
    }
 
    public function AjaxSendMessageAction () {
        $message = $_POST[&#39;message&#39;];
        // 设置GatewayWorker服务的Register服务ip和端口,请根据实际情况改成实际值
        Gateway::$registerAddress = &#39;127.0.0.1:1238&#39;;
 
        GateWay::sendToAll($message);
    }
}

The above is the detailed content of TP5 integrates WorkerMan and GatewayWorker. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!