在TP5根目录 窗口地址栏输入 cmd 通过 composer 安装 GatewayWorker
composer require workerman/workerman-for-win
composer require workerman/GatewayWorker-for-win
composer require workerman/gateway-worker-for-win (如果第二个下载不了,用这个)
如果还没有安装composer
可以通过 https://getcomposer.org/download/
下载,一直按 下一步 就行了
在application目录下,创建一个应用模块,模块名称为gatewayapp,其目录结构如下:
controller/Index.php文件
<?php
namespace app\gatewayapp\controller;
use think\Controller;
class Index extends Controller {
public function index() {
return $this->fetch();
}
}
view/index/index.html视图文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket示例</title>
</head>
<body>
<script type="text/javascript">
var webSocket = null;
initSocket();
function initSocket() {
if (!"WebSocket" in window) {
console.log("您的浏览器不支持 WebSocket!");
return;
}
webSocket = new WebSocket("ws://"+document.domain+":8283");
webSocket.onopen = handleSend;
webSocket.onmessage = handleMessage;
webSocket.onclose = handleClose;
webSocket.onerror = handleError;
}
// 向服务器端发送数据
function handleSend() {
// Web Socket 已连接上,使用 send() 方法发送数据
testing();
}
// 处理服务器端发送过来的数据
function handleMessage(evt) {
var received_msg = evt.data;
console.log(received_msg);
}
// 处理连接关闭事件
function handleClose() {
console.log("连接已关闭...");
}
// 处理WebSocket错误
function handleError() {
console.log("WebSocketError!");
}
function testing() {
//每隔3秒钟向服务器发送数据,此处仅用于测试
var items = ['张三','李四','小二黑','阿杜','单工','大理寺','花荣','刘备','诸葛亮'];
setInterval(function () {
var item = items[Math.floor(Math.random()*items.length)];
webSocket.send(item);
},3000);
}
</script>
</body>
</html>
run/start_register.php文件
<?php
use GatewayWorker\Register;
use Workerman\Worker;
$registerInstance = new GwRegister();
call_user_func_array(array($registerInstance,'index'),array());
class GwRegister {
public function __construct() {
require_once dirname(__FILE__) . '/../../../vendor/autoload.php';
include_once dirname(__FILE__).'/../const.php';
}
public function index() {
// register 必须是text协议
$registerAddress = sprintf('text://%s',GW_REGISTER_PROTOCOL);
$register = new Register($registerAddress);
// 如果不是在根目录启动,则运行runAll方法
if(!defined('GLOBAL_START')) {
Worker::runAll();
}
}
}
run/start_gateway.php文件
<?php
use Workerman\Worker;
use GatewayWorker\Gateway;
use Workerman\Autoloader;
$gatewayInstance = new GwGateway();
call_user_func_array(array($gatewayInstance,'index'),array());
class GwGateway {
private $gatewayAddress;
public function __construct() {
require_once dirname(__FILE__) . '/../../../vendor/autoload.php';
include_once dirname(__FILE__).'/../const.php';
// gateway 进程,这里使用websocket协议
$this->gatewayAddress = sprintf('websocket://%s',GW_GATEWAY_ADDRESS);
}
public function index() {
$gateway = new Gateway($this->gatewayAddress);
// 设置名称,方便status时查看
$gateway->name = GW_GATEWAY_NAME;
// 设置进程数,gateway进程数建议与cpu核数相同
$gateway->count = GW_GATEWAY_COUNT;
// 本机ip,分布式部署时请设置成内网ip(非127.0.0.1)
$gateway->lanIp = GW_LOCAL_HOST_IP;
// 内部通讯起始端口,假如$gateway->count=4,起始端口为4000
// 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口
$gateway->startPort = GW_GATEWAY_START_PORT;
// 服务注册地址
$gateway->registerAddress = GW_REGISTER_ADDRESS;
// 心跳间隔,单位:秒,0 表示不发送心跳检测
$gateway->pingInterval = GW_GATEWAY_PING_INTERVAL;
// 心跳数据
$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();
}
}
}
run/start_businessworker.php文件
<?php
use Workerman\Worker;
use GatewayWorker\BusinessWorker;
use Workerman\Autoloader;
$businessInstance = new GwBusinessWorker();
call_user_func_array(array($businessInstance,'index'),array());
class GwBusinessWorker {
public function __construct() {
require_once dirname(__FILE__) . '/../../../vendor/autoload.php';
include_once dirname(__FILE__).'/../const.php';
}
public function index() {
// bussinessWorker 进程
$worker = new BusinessWorker();
// worker名称
$worker->name = GW_WORKER_NAME;
// bussinessWorker进程数量
$worker->count = GW_BUSINESS_WORKER_COUNT;
// 服务注册地址
$worker->registerAddress = GW_REGISTER_ADDRESS;
//设置处理业务的类,此处制定Events的命名空间
$worker->eventHandler = GW_BUSINESS_EVENT_HANDLER;
// 如果不是在根目录启动,则运行runAll方法
if(!defined('GLOBAL_START')) {
Worker::runAll();
}
}
}
const.php常量定义文件,根据需要,修改相关常量对应的值。
<?php
// 注册协议
define('GW_REGISTER_PROTOCOL','0.0.0.0:1236');
// 注册地址
define('GW_REGISTER_ADDRESS','127.0.0.1:1236');
// 网关地址
define('GW_GATEWAY_ADDRESS','0.0.0.0:8283');
// 网关起始端口
define('GW_GATEWAY_START_PORT','2900');
// 心跳检测间隔,单位:秒,0 表示不发送心跳检测
define('GW_GATEWAY_PING_INTERVAL',10);
// 本机ip,分布式部署时请设置成内网ip(非127.0.0.1)
define('GW_LOCAL_HOST_IP','127.0.0.1');
// 网关名称
define('GW_GATEWAY_NAME','Gateway001');
// worker进程名称
define('GW_WORKER_NAME','BusinessWorker001');
// Gateway进程数量,建议与CPU核数相同
define('GW_GATEWAY_COUNT',2);
// BusinessWorker进程数量,建议设置为CPU核数的1倍-3倍
define('GW_BUSINESS_WORKER_COUNT',6);
// Business业务处理类,可以带命名空间
define('GW_BUSINESS_EVENT_HANDLER','GwEvents');
start_for_win.bat启动文件
php run\start_register.php run\start_gateway.php run\start_businessworker.php
pause
run/GwEvents.php文件
<?php
// namespace app\gatewayapp\controller;
/**
* 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 GwEvents
{
/**
* 当客户端连接时触发
* 如果业务不需此回调可以删除onConnect *
* @param int $client_id 连接id
*/
public static function onConnect($client_id) {
// 向当前client_id发送数据
Gateway::sendToClient($client_id, sprintf('Hello %s',$client_id));
// 向所有人发送
Gateway::sendToAll(sprintf('用户 %s 已登录!',$client_id));
}
/**
* 当客户端发来消息时触发
* @param int $client_id 连接id
* @param mixed $message 具体消息
*/
public static function onMessage($client_id, $message) {
// 向所有人发送
Gateway::sendToAll(sprintf('用户 %s 说:%s',$client_id,$message));
}
/**
* 当用户断开连接时触发
* @param int $client_id 连接id
*/
public static function onClose($client_id) {
// 向所有人发送
GateWay::sendToAll(sprintf('用户 %s 已退出!',$client_id));
}
}
最后
双击start_for_win.bat文件,启动websocket服务,启动成功后的界面如下:
浏览器输入
http://你配置的域名/gatewayapp/Index/Index
F12打开控制台即可看到js打印结果
本文为Pasa吴原创文章,转载无需和我联系,但请注明来自Pasa吴博客https://www.pasawu.top
最新评论