赞
踩
swoole-worker
关于本项目
此项目是workerman(v3.4.5)的swoole移植版本,移除了对pcntl,libevent,event,ev扩展的依赖,转而使用swoole提供的swoole_process和swoole_event,定时器采用swoole的swoole_timer,server采用stream扩展
环境依赖
PHP版本大于等于 5.4 (推荐PHP7及以上版本)
POSIX操作系统(Linux, OSX, BSD)
Posix和Swoole扩展
Swoole扩展版本不小于1.9.18或者不小于2.0.8(2.0.10及其以上版本支持协程)
致谢
workerman Workerman是一款纯PHP开发的开源高性能的PHP socket 服务器框架
swoole PHP的异步、并行、高性能网络通信引擎,使用纯C语言编写
安装
composer require fage1151/swoole-worker
基本用法
用法与workerman兼容
协程用法
Swoole\Coroutine::create(function() {
$redis = new Swoole\Coroutine\Redis();
$res = $redis->connect('127.0.0.1', 6379);
$ret = $redis->incr('coroutine');
$redis->close();
Swoole\Coroutine::create(function() {
$redis = new Swoole\Coroutine\Redis();
$res = $redis->connect('127.0.0.1', 6379);
$ret = $redis->set('coroutine_i', 50);
$redis->close();
});
});
创建空服务
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::add($time_interval, function()
{
echo "task run\n";
});
};
// 运行worker
Worker::runAll();
创建websocket服务
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 4 processes
$ws_worker->count = 4;
// Emitted when new connection come
$ws_worker->onConnect = function($connection)
{
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
$connection->send('hello ' . $data);
};
// Emitted when connection closed
$ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
};
// Run 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");
// 4 processes
$http_worker->count = 4;
// Emitted when data received
$http_worker->onMessage = function($connection, $data)
{
// $_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_FILES are available
var_dump($_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_FILES);
// send data to client
$connection->send("hello world\n");
};
// run all workers</
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。