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

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";};// 运行workerWorker::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");};// 运行所有workersWorker::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";};// 运行所有workersWorker::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 connectionsphp start.php stop php start.php restart php start.php reload 

基准

CPU:      Intel(R) Core(TM) i3-3220 CPU @ 3.30GHz and 4 processors totallyMemory:   8GOS:       Ubuntu 14.04 LTSSoftware: abPHP:      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 requestsCompleted 200000 requestsCompleted 300000 requestsCompleted 400000 requestsCompleted 500000 requestsCompleted 600000 requestsCompleted 700000 requestsCompleted 800000 requestsCompleted 900000 requestsCompleted 1000000 requestsFinished 1000000 requestsServer Software:        workerman/3.1.4Server Hostname:        127.0.0.1Server Port:            1234Document Path:          /Document Length:        5 bytesConcurrency Level:      100Time taken for tests:   7.240 secondsComplete requests:      1000000Failed requests:        0Keep-Alive requests:    1000000Total transferred:      73000000 bytesHTML transferred:       5000000 bytesRequests 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] receivedConnection Times (ms)min  mean[+/-sd] median   maxConnect:        0    0   0.0      0       5Processing:     0    1   0.2      1       9Waiting:        0    1   0.2      1       9Total:          0    1   0.2      1       9Percentage of the requests served within a certain time (ms)50%      166%      175%      180%      190%      195%      198%      199%      1100%      9 (longest request)

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

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

el-table 设置最大高度且能刚好撑满

max-height"calc(90vh - 120px)"90vh视口高度的90%自行调整即可

解决: 使用html2canvas和print-js打印组件时, 超出高度出现空白页

如果所示&#xff1a;当我利用html2canvas转换成图片后, 然后使用print-js打印多张图片, 第一张会出现空白页 打印组件可参考这个: Vue-使用html2canvas和print-js打印组件 解决: 因为是使用html2canvas转换成图片后才打印的, 而图片是行内块级元素, 会有间隙, 所以被挤下去了…

真香!Jenkins 主从模式解决问题So Easy~

01.Jenkins 能干什么 Jenkins 是一个开源软件项目&#xff0c;是基于 Java 开发的一种持续集成工具&#xff0c;用于监控持续重复的工作&#xff0c;旨在提供一个开放易用的软件平台&#xff0c;使软件项目可以进行持续集成。 中文官网&#xff1a;https://jenkins.io/zh/ 0…

Docker基础(CentOS 7)

参考资料 hub.docker.com 查看docker官方仓库&#xff0c;需要梯子 Docker命令大全 黑马程序员docker实操教程 &#xff08;黑马讲的真的不错 容器与虚拟机 安装 yum install -y docker Docker服务命令 启动服务 systemctl start docker停止服务 systemctl stop docker重启…

Redis AOF重写原原理

重写aof之前 appendonly.aof.1.base.aof appendonly.aof.1.incr.aof appendonly.aof.manifest 重写aof 一次 appendonly.aof.2.base.aof 大小变化 appendonly.aof.2.incr.aof 大小o appendonly.aof.manifest 大小不变 AOF文件重写并不是对原文件进行重新整理&#xff0c;而是直…

Docker搭建MySQL8.0主从复制(一主一从)

0. 配置说明 宿主机使用的版本为19045的win10专业版&#xff0c;MySQL使用的是8.0&#xff0c;Docker容器使用Linux。 1. 安装Docker Desktop 略 修改Docker默认安装路径 安装包自己就提供了修改安装路径的功能&#xff0c;CMD中运行&#xff1a; “Docker Desktop Installe…

财务明细一目了然,颜色标记记录轻松掌握个人账目!

无论您是想更好地理清个人收支&#xff0c;还是希望在财务管理中更加高效&#xff0c;我们为您推荐一款绝佳的财政管理神器&#xff1a;颜色标记记录&#xff01; 第一步&#xff0c;首先&#xff0c;我们要先进入【晨曦记账本】主页面&#xff0c;并点击上方功能栏里的“添加…

[开源]MIT协议,开源论坛程序,拥有友好的用户界面和操作体验

一、开源项目简介 尤得一物是一个开源论坛程序&#xff0c;提供丰富的功能&#xff0c;可以作为管理或分享文章的论坛博客&#xff0c;也可以在此基础上进行自定义开发。 二、开源协议 使用MIT开源协议 三、界面展示 四、功能概述 尤得一物是一个开源论坛程序&#xff0c;…

如何使用Docker轻松构建和管理应用程序(一)

如今Docker的使用已经非常普遍&#xff0c;特别在一线互联网公司。使用Docker技术可以帮助企业快速水平扩展服务&#xff0c;从而到达弹性部署业务的能力。在云服务概念兴起之后&#xff0c;Docker的使用场景和范围进一步发展&#xff0c;如今在微服务架构越来越流行的情况下&a…

discuz封面设置失败的解决办法(centos系统+windows系统)

discuz封面设置失败的解决办法(centos系统windows系统&#xff09; centos系统&#xff1a;1、开启/var/www/html 这个目录的读写权限chmod -R 777 /var/www/html然后重启httpd&#xff1a;service httpd restart如果discuz论坛发布帖子&#xff0c;还是显示封面设置失败的话…

云计算安全和云原生安全的关系

云计算安全(Cloud Computing Security)指的是在云环境中保护数据、应用程序和基础设施的安全性。它包括保护云服务提供商的基础设施和平台&#xff0c;以及云服务用户的数据和应用程序。 云原生安全(Cloud-Native Security)则是指在云原生环境中保护应用程序和服务的安全性。云…

基于maven的项目搭建(已跑通)

1、直接选择archetype-webapp即可 &#xff08;这里很多人会觉得很慢–解决方案&#xff1a;https://blog.csdn.net/qq_45591895/article/details/133705674?spm1001.2014.3001.5501&#xff09; 2、手动添加一个java目录即可。 3、添加Tomcat 3、这就跑通了&#xff0c;可以…

二叉搜索树的基础操作

如果对于二叉搜索树不是太清楚&#xff0c;为什么要使用二叉搜索树&#xff1f;作者推荐&#xff1a;二叉搜索树的初步认识_加瓦不加班的博客-CSDN博客 定义节点 static class BSTNode {int key; // 若希望任意类型作为 key, 则后续可以将其设计为 Comparable 接口Object val…

Unity 之 EditorGUILayout.BeginHorizontal/EndHorizontal异常报错问题

报错内容&#xff1a; 缘由&#xff1a;由于在EditorGUILayout.EndHorizontal()之前执行了类似打开窗口的逻辑 解决办法&#xff1a; 在EditorGUILayout.EndHorizontal()之前执行GUIUtility.ExitGUI();

【广州华锐互动】动物解剖学AR互动学习平台

增强现实&#xff08;AR&#xff09;是一种将虚拟信息叠加到现实世界中的技术。通过智能手机、平板电脑或AR眼镜等设备&#xff0c;AR技术可以创建出逼真的虚拟物体&#xff0c;这些物体可以与现实世界的环境相互交互。 AR技术在教育领域的应用非常广泛&#xff0c;包括历史、科…

Python接口自动化测试实战详解,你想要的全都有

前言 接口自动化测试是当前软件开发中最重要的环节之一&#xff0c;可以提高代码质量、加速开发周期、减少手工测试成本等优点。Python语言在接口自动化测试方面应用广泛&#xff0c;因为它具有简单易学、开发效率高、库丰富等特点。 一、接口自动化测试概述 接口自动化测试…

基于docker+Keepalived+Haproxy高可用前后的分离技术

基于dockerKeepalivedHaproxy高可用前后端分离技术 架构图 服务名docker-ip地址docker-keepalived-vip-iphaproxy-01docker-ip自动分配 未指定ip192.168.31.252haproxy-02docker-ip自动分配 未指定ip192.168.31.253 安装haproxy 宿主机ip 192.168.31.254 宿主机keepalived虚…

macOS Sonoma 正式版系统已发布,macos14值得更新吗

北京时间9月27日macOS Sonoma 正式版系统发布&#xff0c;为 Mac 带来一系列丰富新功能&#xff1a;优化小组件、升级视频会议、沉浸式游戏体验等&#xff0c;最新macos14值得更新吗&#xff1f;这里根据我一个月的试用beta版本体验来分享一下。 我使用的是M1芯片的MacBook air…

TimeWise-Jira工时管理插件6.0.0发布!对比测评某知名工时插件,谁的数据处理性能更胜一筹?

近期&#xff0c;龙智自研插件TimeWise for Jira&#xff08;Jira工时管理插件&#xff09;发布了重要更新——6.0.0版本。这次升级主要针对报表性能做出了优化与提升。 对于企业级应用而言&#xff0c;具高效处理大规模数据的能力是最为关键。龙智深谙国内用户需求&#xff0…

基础算法之——【动态规划之路径问题】1

今天更新动态规划路径问题1&#xff0c;后续会继续更新其他有关动态规划的问题&#xff01;动态规划的路径问题&#xff0c;顾名思义&#xff0c;就是和路径相关的问题。当然&#xff0c;我们是从最简单的找路径开始&#xff01; 动态规划的使用方法&#xff1a; 1.确定状态并…