<?php?
require_once __DIR__ . '/vendor/autoload.php';?
use Workerman\Worker;?
$http_worker = new Worker("http://0.0.0.0:2345");
$http_worker->onConnect = function ($connection) {
$connection->protocol = '\\Workerman\\Protocols\\Http';?
};?
\Workerman\Protocols\Http::header('Content-Type:application/json; charset=utf-8');?
$http_worker->onWorkerStart = function ($worker) {
// 將db實(shí)例存儲(chǔ)在全局變量中(也可以存儲(chǔ)在某類的靜態(tài)成員中)
global $db;
$db = new \Workerman\MySQL\Connection('127.0.0.1', '50681', 'root', 'root', 'aqr_develop');
};?
// 接收到瀏覽器發(fā)送的數(shù)據(jù)時(shí)回復(fù)hello world給瀏覽器
$http_worker->onMessage = function ($connection, $data) {
// 通過全局變量獲得db實(shí)例
global $db;
// 執(zhí)行SQL
$all_tables = $db->query('show tables');
$connection->send(json_encode($all_tables));
// $connection->send(PHP_SAPI);
};?
// 運(yùn)行worker
Worker::runAll();
設(shè)置了header頭,無效
請(qǐng)問下,你這邊是怎么設(shè)置header,我按照還是不可以
$io->on('workerStart', function () {
global $httpWorkUrl;
// 監(jiān)聽一個(gè)http端口
$inner_http_worker = new Worker($httpWorkUrl);
// 當(dāng)http客戶端發(fā)來數(shù)據(jù)時(shí)觸發(fā)
$inner_http_worker->onMessage = function ($http_connection, $data) {
global $clientIds, $io;
$_POST = $_POST ? $_POST : $_GET;
echo date('Y-m-d H:i:s') . 'workerStart::: ' . var_export($_POST, true) . PHP_EOL;
if (isset($_POST['type'])) {
global $db, $dbConfig;
$db = new \Medoo\Medoo($dbConfig);
$type = $_POST['type'];
switch ($type) {
case 'chat_group_messages':
$roomId = $_POST['room_id'];
$limit = $_POST['limit'] ?? 10;
$where = [
'room_id[=]' => $roomId,
'ORDER' => ['id' => 'DESC'],
"LIMIT" => $limit,
];
if (!empty($_POST['id'])) {
$where['id[<]'] = $_POST['id'];
}
$messages = $db->select('users_messages', '*', $where);
$data = json_encode([
'status' => 1,
'limit' => $limit,
'list' => $messages,
]);
// $http_connection->setHeader('Content-Type', 'application/json');
\Workerman\Protocols\Http::header('Content-Type:application/json; charset=utf-8');
return $http_connection->send($data);
break;
default:
# code...
break;
}
return $http_connection->send(json_encode(['satus'=>0]));
}
};
// 執(zhí)行監(jiān)聽
$inner_http_worker->listen();
});
if (!defined('GLOBAL_START')) {
Worker::runAll();
}```