workerman的基本用法(示例详解)

news2024/11/15 11:54:28

workerman是什么?

Workerman是一个异步事件驱动的PHP框架,具有高性能,可轻松构建快速,可扩展的网络应用程序。支持HTTP,Websocket,SSL和其他自定义协议。支持libevent,HHVM,ReactPHP。

要求

  • PHP 5.3或更高版本
  • 兼容POSIX的操作系统(Linux,OSX,BSD)
  • 用于PHP的POSIX和PCNTL扩展

安装

composer require workerman/workerman

基本用法

websocket服务器


require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

// 创建一个Websocket服务器

$ws_worker = new Worker("websocket://0.0.0.0:2346");

 

$ws_worker->count = 4;

 

// 在新连接到来时发出

$ws_worker->onConnect = function($connection)

{

    echo "New connection\n";

 };

 

// 接收数据时发出

$ws_worker->onMessage = function($connection, $data)

{

    // Send hello $data

    $connection->send('hello ' . $data);

};

 

// 连接关闭时发出

$ws_worker->onClose = function($connection)

{

    echo "Connection closed\n";

};

 

// 运行worker

Worker::runAll();

http服务器

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

// #### http worker ####

$http_worker = new Worker("http://0.0.0.0:2345");

 

$http_worker->count = 4;

 

// 接收数据时发出

$http_worker->onMessage = function($connection, $data)

{

    //$_GET、$_POST、$_COOKIE、$_SESSION、$_SERVER、$_FILES都是可用的

    var_dump($_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_FILES);

    // 发送数据给客户端

    $connection->send("hello world \n");

};

 

// 运行所有workers

Worker::runAll();

WebServer

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\WebServer;

use Workerman\Worker;

 

// WebServer

$web = new WebServer("http://0.0.0.0:80");

 

$web->count = 4;

 

$web->addRoot('www.your_domain.com', '/your/path/Web');

$web->addRoot('www.another_domain.com', '/another/path/Web');

 

Worker::runAll();

TCP服务器

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

// #### 创建socket并监听1234端口 ####

$tcp_worker = new Worker("tcp://0.0.0.0:1234");

 

$tcp_worker->count = 4;

 

//在新连接到来时发出

$tcp_worker->onConnect = function($connection)

{

    echo "New Connection\n";

};

 

// 接收数据时发出

$tcp_worker->onMessage = function($connection, $data)

{

    // 发送数据给客户端

    $connection->send("hello $data \n");

};

 

// 在新连接到来时发出

$tcp_worker->onClose = function($connection)

{

    echo "Connection closed\n";

};

 

Worker::runAll();

启用SSL

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

// SSL环境

$context = array(

    'ssl' => array(

        'local_cert'  => '/your/path/of/server.pem',

        'local_pk'    => '/your/path/of/server.key',

        'verify_peer' => false,

    )

);

 

// 创建一个带有ssl的Websocket服务器。

$ws_worker = new Worker("websocket://0.0.0.0:2346", $context);

 

// 启用SSL。WebSocket+SSL意味着安全的WebSocket (wss://)。

//类似的Https方法等等。

$ws_worker->transport = 'ssl';

 

$ws_worker->onMessage = function($connection, $data)

{

    // 发送hello $data

    $connection->send('hello ' . $data);

};

 

Worker::runAll();

自定义协议

Protocols/MyTextProtocol.php

namespace Protocols;

/**

 * 用户定义的协议

*格式文本+“\ n”

 */

class MyTextProtocol

{

    public static function input($recv_buffer)

    {

        // 找到“\n”第一个出现的位置

        $pos = strpos($recv_buffer, "\n");

        // 不是一个完整的package。返回0,因为package的长度无法计算

        if($pos === false)

        {

            return 0;

        }

        // 返回package的长度

        return $pos+1;

    }

 

    public static function decode($recv_buffer)

    {

        return trim($recv_buffer);

    }

 

    public static function encode($data)

    {

        return $data."\n";

    }

}

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

// #### MyTextProtocol worker ####

$text_worker = new Worker("MyTextProtocol://0.0.0.0:5678");

 

$text_worker->onConnect = function($connection)

{

    echo "New connection\n";

};

 

$text_worker->onMessage =  function($connection, $data)

{

    // 发送数据给客户端

    $connection->send("hello world \n");

};

 

$text_worker->onClose = function($connection)

{

    echo "Connection closed\n";

};

 

// 运行所有workers

Worker::runAll();

计时器

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

use Workerman\Lib\Timer;

 

$task = new Worker();

$task->onWorkerStart = function($task)

{

    // 2.5秒

    $time_interval = 2.5; 

    $timer_id = Timer::add($time_interval, 

        function()

        {

            echo "Timer run\n";

        }

    );

};

 

//运行

Worker::runAll();

AsyncTcpConnection(tcp / ws / text / frame等...)

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

use Workerman\Connection\AsyncTcpConnection;

 

$worker = new Worker();

$worker->onWorkerStart = function()

{

    //客户端Websocket协议。

    $ws_connection = new AsyncTcpConnection("ws://echo.websocket.org:80");

    $ws_connection->onConnect = function($connection){

        $connection->send('hello');

    };

    $ws_connection->onMessage = function($connection, $data){

        echo "recv: $data\n";

    };

    $ws_connection->onError = function($connection, $code, $msg){

        echo "error: $msg\n";

    };

    $ws_connection->onClose = function($connection){

        echo "connection closed\n";

    };

    $ws_connection->connect();

};

Worker::runAll();

ReactPHP的异步Mysql

composer require react/mysql

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

$worker = new Worker('tcp://0.0.0.0:6161');

$worker->onWorkerStart = function() {

    global $mysql;

    $loop  = Worker::getEventLoop();

    $mysql = new React\MySQL\Connection($loop, array(

        'host'   => '127.0.0.1',

        'dbname' => 'dbname',

        'user'   => 'user',

        'passwd' => 'passwd',

    ));

    $mysql->on('error', function($e){

        echo $e;

    });

    $mysql->connect(function ($e) {

        if($e) {

            echo $e;

        } else {

            echo "connect success\n";

        }

    });

};

$worker->onMessage = function($connection, $data) {

    global $mysql;

    $mysql->query('show databases' /*trim($data)*/, function ($command, $mysql) use ($connection) {

        if ($command->hasError()) {

            $error = $command->getError();

        } else {

            $results = $command->resultRows;

            $fields  = $command->resultFields;

            $connection->send(json_encode($results));

        }

    });

};

Worker::runAll();

ReactPHP的Async Redis

composer require clue/redis-react

require_once __DIR__ . '/vendor/autoload.php';

use Clue\React\Redis\Factory;

use Clue\React\Redis\Client;

use Workerman\Worker;

 

$worker = new Worker('tcp://0.0.0.0:6161');

 

$worker->onWorkerStart = function() {

    global $factory;

    $loop    = Worker::getEventLoop();

    $factory = new Factory($loop);

};

 

$worker->onMessage = function($connection, $data) {

    global $factory;

    $factory->createClient('localhost:6379')->then(function (Client $client) use ($connection) {

        $client->set('greeting', 'Hello world');

        $client->append('greeting', '!');

 

        $client->get('greeting')->then(function ($greeting) use ($connection){

            // Hello world!

            echo $greeting . PHP_EOL;

            $connection->send($greeting);

        });

 

        $client->incr('invocation')->then(function ($n) use ($connection){

            echo 'This is invocation #' . $n . PHP_EOL;

            $connection->send($n);

        });

    });

};

 

Worker::runAll();

Aysnc dns的ReactPHP

composer require react/dns

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

$worker = new Worker('tcp://0.0.0.0:6161');

$worker->onWorkerStart = function() {

    global   $dns;

    // Get event-loop.

    $loop    = Worker::getEventLoop();

    $factory = new React\Dns\Resolver\Factory();

    $dns     = $factory->create('8.8.8.8', $loop);

};

$worker->onMessage = function($connection, $host) {

    global $dns;

    $host = trim($host);

    $dns->resolve($host)->then(function($ip) use($host, $connection) {

        $connection->send("$host: $ip");

    },function($e) use($host, $connection){

        $connection->send("$host: {$e->getMessage()}");

    });

};

 

Worker::runAll();

ReactPHP的Http客户端

composer require react/http-client

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

$worker = new Worker('tcp://0.0.0.0:6161');

 

$worker->onMessage = function($connection, $host) {

    $loop    = Worker::getEventLoop();

    $client  = new \React\HttpClient\Client($loop);

    $request = $client->request('GET', trim($host));

    $request->on('error', function(Exception $e) use ($connection) {

        $connection->send($e);

    });

    $request->on('response', function ($response) use ($connection) {

        $response->on('data', function ($data) use ($connection) {

            $connection->send($data);

        });

    });

    $request->end();

};

 

Worker::runAll();

ReactPHP的ZMQ

composer require react/zmq

require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

$worker = new Worker('text://0.0.0.0:6161');

$worker->onWorkerStart = function() {

    global   $pull;

    $loop    = Worker::getEventLoop();

    $context = new React\ZMQ\Context($loop);

    $pull    = $context->getSocket(ZMQ::SOCKET_PULL);

    $pull->bind('tcp://127.0.0.1:5555');

    $pull->on('error', function ($e) {

        var_dump($e->getMessage());

    });

    $pull->on('message', function ($msg) {

        echo "Received: $msg\n";

    });

};

Worker::runAll();

react的STOMP

composer requirereact/stomp


require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;

 

$worker = new Worker('text://0.0.0.0:6161');

 

$worker->onWorkerStart = function() {

    global   $client;

    $loop    = Worker::getEventLoop();

    $factory = new React\Stomp\Factory($loop);

    $client  = $factory->createClient(array('vhost' => '/', 'login' => 'guest', 'passcode' => 'guest'));

 

    $client

        ->connect()

        ->then(function ($client) use ($loop) {

            $client->subscribe('/topic/foo', function ($frame) {

                echo "Message received: {$frame->body}\n";

            });

        });

};

 

Worker::runAll(); 

可用命令

php start.php start
php start.php start -d

2f960202310071039557166.png

php start.php status [object Object]

php start.php connections

php start.php stop 

php start.php restart 

php start.php reload 

基准

CPU:      Intel(R) Core(TM) i3-3220 CPU @ 3.30GHz and 4 processors totally

Memory:   8G

OS:       Ubuntu 14.04 LTS

Software: ab

PHP:      5.5.9

代码


use Workerman\Worker;

$worker = new Worker('tcp://0.0.0.0:1234');

$worker->count=3;

$worker->onMessage = function($connection, $data)

{

    $connection->send("HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nServer: workerman\r\nContent-Length: 5\r\n\r\nhello");

};

Worker::runAll();

结果

ab -n1000000 -c100 -k http://127.0.0.1:1234/

This is ApacheBench, Version 2.3 <$Revision: 1528965 $>

Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

Licensed to The Apache Software Foundation, http://www.apache.org/

 

Benchmarking 127.0.0.1 (be patient)

Completed 100000 requests

Completed 200000 requests

Completed 300000 requests

Completed 400000 requests

Completed 500000 requests

Completed 600000 requests

Completed 700000 requests

Completed 800000 requests

Completed 900000 requests

Completed 1000000 requests

Finished 1000000 requests

 

 

Server Software:        workerman/3.1.4

Server Hostname:        127.0.0.1

Server Port:            1234

 

Document Path:          /

Document Length:        5 bytes

 

Concurrency Level:      100

Time taken for tests:   7.240 seconds

Complete requests:      1000000

Failed requests:        0

Keep-Alive requests:    1000000

Total transferred:      73000000 bytes

HTML transferred:       5000000 bytes

Requests per second:    138124.14 [#/sec] (mean)

Time per request:       0.724 [ms] (mean)

Time per request:       0.007 [ms] (mean, across all concurrent requests)

Transfer rate:          9846.74 [Kbytes/sec] received

 

Connection Times (ms)

              min  mean[+/-sd] median   max

Connect:        0    0   0.0      0       5

Processing:     0    1   0.2      1       9

Waiting:        0    1   0.2      1       9

Total:          0    1   0.2      1       9

 

Percentage of the requests served within a certain time (ms)

  50%      1

  66%      1

  75%      1

  80%      1

  90%      1

  95%      1

  98%      1

  99%      1

 100%      9 (longest request)

以上就是workerman的基本用法(示例详解)的详细内容

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1074444.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

朋友一口气拿下字节27K的offer,实名羡慕了....

最近有朋友去字节面试&#xff0c;面试前后进行了20天左右&#xff0c;包含4轮电话面试、1轮笔试、1轮主管视频面试、1轮hr视频面试。 据他所说&#xff0c;80%的人都会栽在第一轮面试&#xff0c;要不是他面试前做足准备&#xff0c;估计都坚持不完后面几轮面试。 其实&…

DRM全解析 —— framebuffer详解(1)

本文参考以下博文&#xff1a; Linux内核4.14版本——drm框架分析(1)——drm简介 特此致谢&#xff01; 1. 简介 framebuffer是一块内存区域&#xff0c;可以理解为一块画布&#xff0c;驱动和应用层都能访问它。绘制前需要将它格式化&#xff0c;设定绘制的色彩模式&#x…

leetcode:217. 存在重复元素(python3解法)

难度&#xff1a;简单 给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 &#xff0c;返回 true &#xff1b;如果数组中每个元素互不相同&#xff0c;返回 false 。 示例 1&#xff1a; 输入&#xff1a;nums [1,2,3,1] 输出&#xff1a;true 示例 2&#xff1a; 输…

DruidDataSource导致OOM问题处理

DruidDataSource导致OOM问题处理 起因分析日志分析Dump文件问题分析处理 起因 一个平凡的工作日&#xff0c;我像往常一样完成产品提出的需求的业务代码&#xff0c;突然收到了监控平台发出的告警信息。本以为又是一些业务上的 bug 导致的报错&#xff0c;一看报错发现日志写着…

Deepwalk,Node2vec算法原理生动理解(图文)

Deepwalk算法原理详解 DeepWalk算法之所以能够有效地学习节点的低维表示&#xff0c;是因为它利用了本质上与自然语言处理相同的思路&#xff1a;图是一种高维数据&#xff0c;很难直接处理&#xff0c;但是可以将其映射到低维空间中&#xff0c;这样可以更好地进行处理 Deep…

ElasticSearch 使用 searchAfter() 进行遍历查询 查到的数据总数小于 totalHits

ElasticSearch 使用 searchAfter() 进行遍历查询&#xff0c;查到的数据总数小于 totalHits&#xff0c;并且每次查询的页 size 越大&#xff0c;遍历总数和 totalHits 的差距越小。 原因 这是由于如下的机制&#xff1a; 每个文档具有一个唯一值的字段应该用作排序规范的仲裁…

2023 IDC中国数字金融论坛丨中电金信向行业分享“源启+应用重构”新范式

9月8日&#xff0c;IDC主办的“2023 IDC中国数字金融论坛”在北京召开。中电金信受邀参会&#xff0c;并带来了深度数字化转型趋势之下关于应用重构的分享与洞见。 论坛重点关注金融科技创新发展趋势与数字化转型之路&#xff0c;中电金信副总经理、研究院院长况文川带来了“创…

多无人机编队集群飞行

matlab2016b可直接运行 多无人机集群编队飞行&#xff08;8架无人机&#xff09;资源-CSDN文库

S7-1200PLC与力控通过S7协议进行通信的具体步骤示例

S7-1200PLC与力控通过S7协议进行通信的具体步骤示例 准备条件: TIA PORTAL V16 力控7.2 SP3 PLC:1214 DC/DC/DC PLC一侧的配置: PLC IP设置为192.168.2.10 PLC属性中的连接机制,勾选允许来自远程对象的PUT/GET 新建一个名为FirstDB的数据块,数据块编号为1 在FirstDB中添加…

大屏设计器项目部署详细步骤

一.项目效果图 二.部署步骤 1.nginx配置前端配置 #gzip on;server {listen 48009;server_name analyse;location / {root /home/designer/dist;index index.html;try_files $uri

vue中v-model的原理是什么?v-model作用在组件上的原理是什么?sync修饰符的原理是什么?

vue中v-model的原理是什么&#xff1f; 特点&#xff1a;双向绑定 数据>视图 视图>数据 场景&#xff1a; 收集表单数据组件上 原理&#xff1a; v-model只是个语法题&#xff0c;本质是&#xff1a;v-model v-bind (:value) v-on (input) <template><…

蓝牙资讯|三星推迟发布智能戒指Galaxy Ring,智能穿戴小型化是大趋势

根据外媒 The Elec 报道&#xff0c;Galaxy Ring这款戒指主要面向健康和 XR 头显市场&#xff0c;该智能戒指可能被延期至 2024 年第三季度后发布。 外媒声称三星 Galaxy Ring 的上市周期&#xff0c;主要取决医疗认证的相关审批时间&#xff0c;三星计划将在 2024 年第三季度…

2023年软件测试工具总结 —— 性能测试工具

软件性能测试的目标是识别应用程序中的所有性能瓶颈。一个软件系统的性能不仅取决于系统本身的设计和编码&#xff0c;而且取决于系统所依赖的运行环境。系统的运行环境会依赖于一些关键因素&#xff0c;例如&#xff1a;系统架构、硬件配置、网络带宽、配套的软件如数据库和中…

java多线程卖电影票的三种实现方式

java多线程卖电影票的三种实现方式 一、需求描述二、实现方式1、继承Thread类的方式2、实现Runnable接口的方式3、使用Lock锁的方式 一、需求描述 某电影院目前正在上映国产大片&#xff0c;共有1000张票&#xff0c;而它有2个窗口卖票&#xff0c;请设计一个程序模拟该电影院…

12.3 实现模拟鼠标录制回放

本节将向读者介绍如何使用键盘鼠标操控模拟技术&#xff0c;键盘鼠标操控模拟技术是一种非常实用的技术&#xff0c;可以自动化执行一些重复性的任务&#xff0c;提高工作效率&#xff0c;在Windows系统下&#xff0c;通过使用各种键盘鼠标控制函数实现动态捕捉和模拟特定功能的…

Ubuntu22.04.3安装教程

虚拟机系列文章 VMware Workstation Player 17 免费下载安装教程 VMware Workstation 17 Pro 免费下载安装教程 windows server 2012安装教程 Ubuntu22.04.3安装教程 FTP服务器搭建 Ubuntu22.04.3安装教程 虚拟机系列文章前言Ubuntu22.04.3安装&#xff08;图文&#xff09; 前…

【C++心愿便利店】No.7---C++之运算符重载

文章目录 前言一、运算符重载的引用二、运算符重载三、赋值运算符重载四、日期类的实现五、const成员六、取地址及const取地址操作符重载 前言 &#x1f467;个人主页&#xff1a;小沈YO. &#x1f61a;小编介绍&#xff1a;欢迎来到我的乱七八糟小星球&#x1f31d; &#x1f…

onlyoffice历史版本功能实现

一&#xff1a;开启客户端配置 如果不开启&#xff0c;回调请求里面的history和changeUrl是空 二&#xff1a;客户端主要实现2个回调函数 1.实现onRequestHistory事件&#xff0c;该事件会在ui点击查看历史的时候发起,用于展示历史列表 关键在于获取到history的内容&#xff…

Vscode进行远程开发

之前用的是pycharm&#xff0c;但是同事说pycharm太重了&#xff0c;连接远程服务器的时候给远程服务器的压力比较大&#xff0c;有时候远程服务器可能都扛不住&#xff0c;所以换成了vscode。 参考博客 手把手教你配置VS Code远程开发工具&#xff0c;工作效率提升N倍 - 知…

【自动驾驶】PETR/PETRv2/StreamPETR论文分析

1.PETR PETR网络结构如下&#xff0c;主要包括image-backbone, 3D Coordinates Generator, 3D Position Encoder, transformer Decoder 1.1 Images Backbone 采用resnet 或者 vovNet,下面的x表示concatenate 1.2 3D Coordinates Generator 坐标生成跟lss类似&#xff0c;假…