File tree Expand file tree Collapse file tree 3 files changed +30
-4
lines changed Expand file tree Collapse file tree 3 files changed +30
-4
lines changed Original file line number Diff line number Diff line change @@ -22,7 +22,7 @@ class Client
22
22
{
23
23
protected Coroutine \Http \Client $ client ;
24
24
25
- public function __construct (protected UriInterface $ uri )
25
+ public function __construct (protected UriInterface $ uri, array $ headers = [] )
26
26
{
27
27
$ host = $ uri ->getHost ();
28
28
$ port = $ uri ->getPort ();
@@ -33,7 +33,7 @@ public function __construct(protected UriInterface $uri)
33
33
}
34
34
35
35
$ this ->client = new Coroutine \Http \Client ($ host , $ port , $ ssl );
36
-
36
+ $ headers && $ this -> client -> setHeaders ( $ headers );
37
37
parse_str ($ this ->uri ->getQuery (), $ query );
38
38
39
39
$ query = http_build_query ($ query );
Original file line number Diff line number Diff line change 20
20
21
21
class ClientFactory
22
22
{
23
- public function create (string $ uri , bool $ autoClose = true ): Client
23
+ public function create (string $ uri , bool $ autoClose = true , array $ headers = [] ): Client
24
24
{
25
25
if (! Str::startsWith ($ uri , ['ws:// ' , 'wss:// ' ])) {
26
26
$ uri = 'ws:// ' . $ uri ;
27
27
}
28
- $ client = make (Client::class, ['uri ' => new Uri ($ uri )]);
28
+ $ client = make (Client::class, ['uri ' => new Uri ($ uri ), ' headers ' => $ headers ]);
29
29
if ($ autoClose ) {
30
30
defer (function () use ($ client ) {
31
31
$ client ->close ();
Original file line number Diff line number Diff line change 12
12
13
13
namespace HyperfTest \WebSocketClient ;
14
14
15
+ use Hyperf \Codec \Json ;
15
16
use Hyperf \HttpMessage \Uri \Uri ;
16
17
use Hyperf \WebSocketClient \Client ;
17
18
use Hyperf \WebSocketClient \Exception \ConnectException ;
@@ -31,4 +32,29 @@ public function testClientConnectFailed()
31
32
32
33
new Client (new Uri ('ws://172.168.1.1:9522 ' ));
33
34
}
35
+
36
+ public function testClientConnected ()
37
+ {
38
+ $ client = new Client (new Uri ('ws://127.0.0.1:10002/ws ' ));
39
+
40
+ $ client ->push ('ping ' );
41
+
42
+ $ this ->assertSame ('pong ' , $ client ->recv (1 )->data );
43
+
44
+ $ client ->close ();
45
+ }
46
+
47
+ public function testClientHeaders ()
48
+ {
49
+ $ client = new Client (new Uri ('ws://127.0.0.1:10002/ws ' ), ['x-token ' => $ token = uniqid ()]);
50
+
51
+ $ client ->push ('headers ' );
52
+
53
+ $ data = $ client ->recv (1 );
54
+ $ headers = Json::decode ($ data ->data );
55
+
56
+ $ this ->assertSame ($ token , $ headers ['x-token ' ]);
57
+
58
+ $ client ->close ();
59
+ }
34
60
}
You can’t perform that action at this time.
0 commit comments