Skip to content

Commit 297bbf2

Browse files
Support to set headers for websocket-client.
Co-authored-by: 李铭昕 <[email protected]>
1 parent ffd97e5 commit 297bbf2

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

src/Client.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Client
2222
{
2323
protected Coroutine\Http\Client $client;
2424

25-
public function __construct(protected UriInterface $uri)
25+
public function __construct(protected UriInterface $uri, array $headers = [])
2626
{
2727
$host = $uri->getHost();
2828
$port = $uri->getPort();
@@ -33,7 +33,7 @@ public function __construct(protected UriInterface $uri)
3333
}
3434

3535
$this->client = new Coroutine\Http\Client($host, $port, $ssl);
36-
36+
$headers && $this->client->setHeaders($headers);
3737
parse_str($this->uri->getQuery(), $query);
3838

3939
$query = http_build_query($query);

src/ClientFactory.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@
2020

2121
class ClientFactory
2222
{
23-
public function create(string $uri, bool $autoClose = true): Client
23+
public function create(string $uri, bool $autoClose = true, array $headers = []): Client
2424
{
2525
if (! Str::startsWith($uri, ['ws://', 'wss://'])) {
2626
$uri = 'ws://' . $uri;
2727
}
28-
$client = make(Client::class, ['uri' => new Uri($uri)]);
28+
$client = make(Client::class, ['uri' => new Uri($uri), 'headers' => $headers]);
2929
if ($autoClose) {
3030
defer(function () use ($client) {
3131
$client->close();

tests/ClientTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
namespace HyperfTest\WebSocketClient;
1414

15+
use Hyperf\Codec\Json;
1516
use Hyperf\HttpMessage\Uri\Uri;
1617
use Hyperf\WebSocketClient\Client;
1718
use Hyperf\WebSocketClient\Exception\ConnectException;
@@ -31,4 +32,29 @@ public function testClientConnectFailed()
3132

3233
new Client(new Uri('ws://172.168.1.1:9522'));
3334
}
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+
}
3460
}

0 commit comments

Comments
 (0)