php 连接 workerman 服务推送
# 通过 composer 安装 workerman "workerman/workerman": "^4.1", "workerman/gatewayclient": "^3.0", "workerman/gateway-worker": "^3.1", # api 新建文件 workerman 放 Events.php ,start_businessworker.php ,start_gateway.php,start_register.php 文件
Events.php
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* 用于检测业务代码死循环或者长时间阻塞等问题
* 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
* 然后观察一段时间workerman.log看是否有process_timeout异常
*/
//declare(ticks=1);
use \GatewayWorker\Lib\Gateway;
/**
* 主逻辑
* 主要是处理 onConnect onMessage onClose 三个方法
* onConnect 和 onClose 如果不需要可以不用实现并删除
*/
class Events
{
/**
* 当客户端连接时触发
* 如果业务不需此回调可以删除onConnect
*
* @param int $client_id 连接id
*/
public static function onConnect($client_id)
{
// 向当前client_id发送数据
Gateway::sendToClient($client_id, json_encode(array(
'client_id' => $client_id
)));
// 向所有人发送
//Gateway::sendToAll("$client_id 风起时");
}
/**
* 当客户端发来消息时触发
* @param int $client_id 连接id
* @param mixed $message 具体消息
*/
public static function onMessage($client_id, $message)
{
// 向所有人发送
//Gateway::sendToAll("$client_id said $message\r\n");
//echo $message;
}
/**
* 当用户断开连接时触发
* @param int $client_id 连接id
*/
public static function onClose($client_id)
{
// 向所有人发送
//GateWay::sendToAll("$client_id logout\r\n");
}
// 进程启动时设置个定时器。Events中支持onWorkerStart需要Gateway版本>=2.0.4
/*public static function onWorkerStart()
{
\Workerman\Timer::add(1, function(){
echo "fengqishi\n";
\app\common\model\CharteredBusCancelCause::create(['cause' => rand(100, 999)]);
});
}*/
}
start_businessworker.php
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;
// 自动加载类
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/Events.php';
// bussinessWorker 进程
$worker = new BusinessWorker();
// worker名称
$worker->name = 'landian';
// bussinessWorker进程数量
$worker->count = 1;
// 服务注册地址
$worker->registerAddress = '127.0.0.1:1241';
$worker->eventHandler = "Events";
// 如果不是在根目录启动,则运行runAll方法
if(!defined('GLOBAL_START'))
{
Worker::runAll();
}
start_gateway.php
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;
// 自动加载类
require_once __DIR__ . '/../../../vendor/autoload.php';
// gateway 进程,这里使用Text协议,可以用telnet测试
$gateway = new Gateway("websocket://0.0.0.0:2346");
// gateway名称,status方便查看
$gateway->name = 'landian';
// gateway进程数
$gateway->count = 4;
// 本机ip,分布式部署时使用内网ip
$gateway->lanIp = '127.0.0.1';
// 内部通讯起始端口,假如$gateway->count=4,起始端口为4000
// 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口
$gateway->startPort = 4004;
// 服务注册地址1236
$gateway->registerAddress = '127.0.0.1:1241';
// 心跳间隔
$gateway->pingInterval = 10;
// 心跳数据
$gateway->pingData = '{"type":"ping"}';
/*
// 当客户端连接上来时,设置连接的onWebSocketConnect,即在websocket握手时的回调
$gateway->onConnect = function($connection)
{
$connection->onWebSocketConnect = function($connection , $http_header)
{
// 可以在这里判断连接来源是否合法,不合法就关掉连接
// $_SERVER['HTTP_ORIGIN']标识来自哪个站点的页面发起的websocket链接
if($_SERVER['HTTP_ORIGIN'] != 'http://kedou.workerman.net')
{
$connection->close();
}
// onWebSocketConnect 里面$_GET $_SERVER是可用的
// var_dump($_GET, $_SERVER);
};
};
*/
// 如果不是在根目录启动,则运行runAll方法
if(!defined('GLOBAL_START'))
{
Worker::runAll();
}
start_register.php
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use \Workerman\Worker;
use \GatewayWorker\Register;
// 自动加载类
require_once __DIR__ . '/../../../vendor/autoload.php';
// register 必须是text协议
$register = new Register('text://0.0.0.0:1241');
// 如果不是在根目录启动,则运行runAll方法
if(!defined('GLOBAL_START'))
{
Worker::runAll();
}
# 根目录下新建 start.php
<?php
/**
* run with command
* php start.php start
*/
ini_set('display_errors', 'on');
use Workerman\Worker;
if(strpos(strtolower(PHP_OS), 'win') === 0)
{
exit("start.php not support windows, please use start_for_win.bat\n");
}
// 检查扩展
if(!extension_loaded('pcntl'))
{
exit("Please install pcntl extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}
if(!extension_loaded('posix'))
{
exit("Please install posix extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}
// 标记是全局启动
define('GLOBAL_START', 1);
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_PATH', __DIR__ . DS);
require_once __DIR__ . '/vendor/autoload.php';
// 加载所有Applications/*/start.php,以便启动所有服务
foreach(glob(__DIR__.'/application/api/fengqishi/start*.php') as $start_file)
{
require_once $start_file;
}
// 运行所有服务
Worker::runAll();
启动 workerman 服务 php start.php start 守护进程 php start.php start -d
停止 workerman 服务 php start.php stop
重启 workerman 服务 php start.php restart
Workerman服务状态 php start.php status
# 前段连接 workerman 在伪静态设置
location /wss {
proxy_pass http://127.0.0.1:2346;
proxy_connect_timeout 30s;
proxy_read_timeout 86400s;
proxy_send_timeout 30s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
注意:修改start_gateway.php文件24行端口号,修改35行端口号;同时需要修改 start_businessworker.php文件,start_register.php文件
默认端口是 1236
use GatewayClient\Gateway;
# 绑定操作 public function bindClientId(){ $client_id = $this->request->post('client_id', ''); adlog("打印:",$client_id); $user_id = 1; //用户ID if ($client_id){ Gateway::bindUid($client_id, $user_id); } $this->success(); }
# 推送操作 public function demo(){ $id = 1; Gateway::sendToUid($id,json_encode([ 'type' => 'order', ])); echo "<pre>"; var_dump(1111); }
思路就是:用户登录的时候或者断线重连的时候绑定下client_id,这个是前端传给你的,把这个client_id跟当前登录的用户进行绑定,然后推送消息的时候推送到用户就行了
# 前段需要连接地址
ws://域名/wss
<?php namespace app\command; use GatewayClient\Gateway; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; use think\db\exception\DataNotFoundException; use think\db\exception\ModelNotFoundException; use think\Exception; use think\exception\DbException; use think\Hook; use Workerman\Worker; use Workerman\Lib\Timer; use function config; // 自动加载类 //require_once ADDON_PATH . 'wanlshop' . DS . 'library' . DS . 'GatewayWorker' . DS . 'vendor' . DS . 'autoload.php'; class Order extends Command { protected function configure() { $this->setName('executedemo') //改下名字 ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start') ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.') ->setDescription('Fengqishi order refund planning task'); } protected function execute(Input $input, Output $output) { $action = $input->getArgument('action'); if (DIRECTORY_SEPARATOR !== '\\') { if (!in_array($action, ['start', 'stop', 'reload', 'restart', 'status', 'connections'])) { $output->writeln("<error>Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .</error>"); return false; } global $argv; array_shift($argv); array_shift($argv); array_unshift($argv, 'think', $action); } elseif ('start' != $action) { $output->writeln("<error>Not Support action:{$action} on Windows.</error>"); return false; } if ('start' == $action) { $output->writeln('Starting GatewayWorker server...'); } // 启动计划任务 $this->plan(); Worker::runAll(); } // 初始化 计划任务 进程 public function plan() { // 全局静态属性 if ($this->input->hasOption('daemon')) { // 以daemon(守护进程)方式运行 Worker::$daemonize = true; } Worker::$pidFile = '/var/run/wanlorder.pid'; $worker = new Worker(); $worker->count = 1; $worker->onWorkerStart = function ($worker) { echo "\r\n"; echo "计划任务 启动成功"; echo "\r\n"; //取消订单 Timer::add(5, array($this, 'demo1')); //5 秒执行 demo1 方法 }; } /** * 处理业务逻辑 * @return void * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public function demo1() { echo '执行成功'; } } #tp5 socke 定时任务 #app 创建 command 目录 创建Order.php # 启动 php think feidachuzu start 计划任务 # 启动 php think feidachuzu start -d 常驻计划任务
WebSocket 在线测试 http://www.websocket-test.com/

浙公网安备 33010602011771号