第一种方法: 使用websocket (workMan)
服务端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
use Workerman\Worker; require_once __DIR__ .'/vendor/autoload.php'; $worker = new Worker('Text://0.0.0.0:5678'); $worker->count = 1; $worker->name = 'Test'; $worker->onMessage = function($connection, $buffer) { $data = json_decode($buffer, true); sleep(3); // 返回推送结果 $connection->send(json_encode($data)); }; $worker->listen(); Worker::runAll(); |
客户端:
1 2 3 4 5 6 7 8 |
// 建立socket连接到内部推送端口 $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1); // 推送的数据,包含uid字段,表示是给这个uid推送 $data = array('uid'=>'uid1', 'percent'=>'tianming'); // 发送数据,注意5678端口是Text协议的端口,Text协议需要在数据末尾加上换行符 fwrite($client, json_encode($data)."\n"); // 读取推送结果 echo fread($client, 8192); |
第二种: 使用 http 请求 (swoole)
服务端:
1 2 3 4 5 6 7 8 9 10 |
<?php $http = new Swoole\Http\Server("127.0.0.1", 9501); $http->on("start", function ($server) { echo "Swoole http server is started at http://127.0.0.1:9501\n"; }); $http->on("request", function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello World\n"); }); $http->start(); |
客户端:
1 |
file_get_contents('http://127.0.0.1:5678'); |
第三种: Task 微任务
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$server = new Swoole\Server("127.0.0.1", 9502); $server->set(array('task_worker_num' => 4)); $server->on('receive', function($server, $fd, $reactor_id, $data) { $task_id = $server->task("Async"); print_r($fd); print_r($reactor_id); echo "收到Task消息: [id=$task_id]\n"; print_r($data); }); $server->on('task', function ($server, $task_id, $reactor_id, $data) { echo "Task[id=$task_id]\n"; print_r($reactor_id); $server->finish(json_encode($data)); }); $server->on('finish', function ($server, $task_id, $data) { echo "AsyncTask[$task_id] finished: {$data}\n"; }); $server->start(); |
服务端:
1 2 3 4 5 6 7 8 9 |
// 建立socket连接到内部推送端口 $client = stream_socket_client('tcp://127.0.0.1:9502', $errno, $errmsg, 1); // 推送的数据,包含uid字段,表示是给这个uid推送 $data = array('uid'=>'uid1', 'percent'=>'88%'); // 发送数据,注意5678端口是Text协议的端口,Text协议需要在数据末尾加上换行符 fwrite($client, json_encode($data)."\n"); echo '任务投递完成'; print_r($errmsg); print_r($errno); |