Skip to content

Commit

Permalink
Support to set headers for websocket-client.
Browse files Browse the repository at this point in the history

Co-authored-by: 李铭昕 <[email protected]>
  • Loading branch information
YunzhiYike and limingxinleo authored Mar 28, 2024
1 parent ffd97e5 commit 297bbf2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Client
{
protected Coroutine\Http\Client $client;

public function __construct(protected UriInterface $uri)
public function __construct(protected UriInterface $uri, array $headers = [])
{
$host = $uri->getHost();
$port = $uri->getPort();
Expand All @@ -33,7 +33,7 @@ public function __construct(protected UriInterface $uri)
}

$this->client = new Coroutine\Http\Client($host, $port, $ssl);

$headers && $this->client->setHeaders($headers);
parse_str($this->uri->getQuery(), $query);

$query = http_build_query($query);
Expand Down
4 changes: 2 additions & 2 deletions src/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@

class ClientFactory
{
public function create(string $uri, bool $autoClose = true): Client
public function create(string $uri, bool $autoClose = true, array $headers = []): Client
{
if (! Str::startsWith($uri, ['ws://', 'wss://'])) {
$uri = 'ws://' . $uri;
}
$client = make(Client::class, ['uri' => new Uri($uri)]);
$client = make(Client::class, ['uri' => new Uri($uri), 'headers' => $headers]);
if ($autoClose) {
defer(function () use ($client) {
$client->close();
Expand Down
26 changes: 26 additions & 0 deletions tests/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

namespace HyperfTest\WebSocketClient;

use Hyperf\Codec\Json;
use Hyperf\HttpMessage\Uri\Uri;
use Hyperf\WebSocketClient\Client;
use Hyperf\WebSocketClient\Exception\ConnectException;
Expand All @@ -31,4 +32,29 @@ public function testClientConnectFailed()

new Client(new Uri('ws://172.168.1.1:9522'));
}

public function testClientConnected()
{
$client = new Client(new Uri('ws://127.0.0.1:10002/ws'));

$client->push('ping');

$this->assertSame('pong', $client->recv(1)->data);

$client->close();
}

public function testClientHeaders()
{
$client = new Client(new Uri('ws://127.0.0.1:10002/ws'), ['x-token' => $token = uniqid()]);

$client->push('headers');

$data = $client->recv(1);
$headers = Json::decode($data->data);

$this->assertSame($token, $headers['x-token']);

$client->close();
}
}

0 comments on commit 297bbf2

Please sign in to comment.