上篇介紹了workman實(shí)現(xiàn)websocket功能(鏈接:https://blog.csdn.net/weixin_38155824/article/details/128952037)
后傳:解決workman部署到Linux環(huán)境無(wú)法啟動(dòng)和連接的問(wèn)題(https://blog.csdn.net/weixin_38155824/article/details/129004050)
這篇就介紹如何在thinkPHP6項(xiàng)目中接入workman。
利用TP6的自定義命令開(kāi)啟websocket服務(wù)
查看TP6手冊(cè):命令行=>自定義命令
第一步,執(zhí)行以下命令,就會(huì)會(huì)生成一個(gè)app\command\Chat命令行指令類.
php think make:command Chat startChat
第二步,配置config/console.php文件
<?php
return [
'commands' => [
'chat' => 'app\command\Chat',
]
];
第三步,測(cè)試-命令幫助-命令行下運(yùn)行
php think
輸出
執(zhí)行
php think chat
自定義命令搞定后,就可以引入workman了
在項(xiàng)目根目錄下通過(guò)comoser安裝workman:
composer require workerman/workerman
然后將上一篇的workman開(kāi)啟wetsocket服務(wù)的代碼復(fù)制到新創(chuàng)建的自定義命令類Chat.php中
(劃重點(diǎn):要引入vendor目錄下的autoload.php,路徑要寫對(duì))
(劃重點(diǎn):要引入vendor目錄下的autoload.php,路徑要寫對(duì))
(劃重點(diǎn):要引入vendor目錄下的autoload.php,路徑要寫對(duì))文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-607986.html
<?php
declare (strict_types = 1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require __DIR__ . '/../../vendor/autoload.php';
class Chat extends Command
{
protected function configure()
{
// 指令配置
$this->setName('startChat')
->setDescription('the startChat command');
}
protected function execute(Input $input, Output $output)
{
// 指令輸出
$output->writeln('startChat');
//啟動(dòng)workman-websocket服務(wù)
// 注意:這里與上個(gè)例子不同,使用的是websocket協(xié)議
$ws_worker = new Worker("websocket://0.0.0.0:2000");
// 啟動(dòng)4個(gè)進(jìn)程對(duì)外提供服務(wù)
$ws_worker->count = 4;
// 當(dāng)收到客戶端發(fā)來(lái)的數(shù)據(jù)后返回hello $data給客戶端
$ws_worker->onMessage = function(TcpConnection $connection, $data)
{
//在控制臺(tái)打印客戶端發(fā)送過(guò)來(lái)的消息
var_dump($data);
var_export($data);
// 向客戶端發(fā)送hello $data
$connection->send('hello ' . $data);
};
// 運(yùn)行worker
Worker::runAll();
}
}
然后再執(zhí)行一下命令:php think chat
輸出:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-607986.html
到了這里,關(guān)于thinkPHP6接入workman的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!