-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp2-client.php
More file actions
74 lines (59 loc) · 1.92 KB
/
Copy pathhttp2-client.php
File metadata and controls
74 lines (59 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
declare(strict_types=1);
/**
* HTTP/2 Client 示例 — 基于 Workerman AsyncTcpConnection
*
* 使用方式:
* php examples/http2-client.php
*
* 通过 http2:// 协议连接,encode() 自动将数组编码为 HTTP/2 帧,
* 无需手动构造帧。
*/
require_once __DIR__ . '/../vendor/autoload.php';
use Protocols\Http2;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\ConnectionInterface;
use Workerman\Worker;
$worker = new Worker();
$worker->onWorkerStart = function () {
$conn = new AsyncTcpConnection('http2://127.0.0.1:8080');
// ---- 连接建立 ----
$conn->onConnect = function (ConnectionInterface $conn) {
echo "[client] connected\n";
Http2::initConnection($conn);
// 通过 encode() 发送请求,stream_id 自动分配(1, 3, 5, ...)
$conn->send([
':method' => 'GET',
':path' => '/',
':scheme' => 'http',
':authority'=> '127.0.0.1:8080',
]);
$conn->send([
':method' => 'GET',
':path' => '/api',
':scheme' => 'http',
':authority'=> '127.0.0.1:8080',
]);
echo "[client] requests sent\n";
};
// ---- 接收响应 ----
$conn->onMessage = function (ConnectionInterface $conn, $data) {
// $data 可能是 null(连接级帧)或完整请求数组
if ($data === null) {
return;
}
echo "[client] stream={$data['stream_id']} response received\n";
// 打印响应头
foreach ($data['headers'] as [$name, $value]) {
echo " {$name}: {$value}\n";
}
echo " body: {$data['body']}\n";
};
// ---- 连接关闭 ----
$conn->onClose = function (ConnectionInterface $conn) {
echo "[client] disconnected\n";
Http2::destroyConnection($conn);
};
$conn->connect();
};
Worker::runAll();