GatewayWorker基于Workerman开发的一个框架,支持多协议多端口监听,支持分布式多机部署,用于快速开发长连接应用,例如移动通讯、物联网、智能家居、游戏服务端、聊天室等等。
- 准备好TP5项目
- SSH登录服务器,切换到项目根目录执行命令
composer require workerman/gateway-worker
或者官方下载压缩包上传,引入vendor工具类
注意看目录结构,以及官方手册
├── Applications // 这里是所有开发者应用项目
│ └── YourApp // 其中一个项目目录,目录名可以自定义
│ ├── Events.php // 开发者只需要关注这个文件
│ ├── start_gateway.php // gateway进程启动脚本,包括端口号等设置
│ ├── start_businessworker.php // businessWorker进程启动脚本
│ └── start_register.php // 注册服务启动脚本
│
├── start.php // 全局启动脚本,此脚本会依次加载Applications/项目/start_*.php启动脚本
│
└── vendor // GatewayWorker框架和Workerman框架源码目录,此目录开发者不用关心
- 项目根目录创建start.php启用文件
<?php
define('APP_PATH', __DIR__ . '/application/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');
define('BIND_MODULE','push/Gatestart');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';
// 运行所有服务
Worker::runAll();
- 在/application/push/controller/目录下创建Gateway启动的控制器文件Gatestart.php
<?php
namespace app\push\controller;
use \Workerman\Worker;
use \GatewayWorker\Register;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;
class Gatestart extends Worker{
public function __construct(){
//初始化register
new Register('text://0.0.0.0:1238');
//初始化 bussinessWorker 进程
$worker = new BusinessWorker();
$worker->name = 'mygate';
$worker->count = 4;
$worker->registerAddress = '127.0.0.1:1238';
//设置处理业务的类,此处制定Events的命名空间
// $worker->eventHandler = '\app\push\controller\Events';
// 初始化 gateway 进程
$context = array(
'ssl' => array(//证书路径
'local_cert' => '/www/server/panel/vhost/cert/www.oceancode.top/fullchain.pem', // 或者crt文件
'local_pk' => '/www/server/panel/vhost/cert/www.oceancode.top/privkey.pem',
'verify_peer' => false
)
);
$gateway = new Gateway("websocket://0.0.0.0:8383",$context);
$gateway->transport = 'ssl';//开启ssl
$gateway->name = 'push';
$gateway->count = 1;
$gateway->lanIp = '127.0.0.1';
$gateway->startPort = 2900;
$gateway->pingInterval = 10;
$gateway->pingData = '{"type":"ping"}';
$gateway->registerAddress = '127.0.0.1:1238';
//运行所有Worker;
Worker::runAll();
}
}
- 跑到项目根目录执行
php start.php start
- 看到下面这个就成功了
- 从前端测试一下
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>链接状态:<span id="state"></span></p>
</body>
</html>
<script language="javascript">
ws = new WebSocket("wss://www.oceancode.top:8383");//SSL用域名访问
ws.onopen = function () {
document.getElementById('state').innerHTML = '链接成功'
ws.send('tom');
// console.log(ws.readyState)
};
// document.getElementById('state').innerHTML = '链接失败'
ws.onmessage = function (e) {
};
</script>