hyperf/docs/en/websocket-client.md

56 lines
1.8 KiB
Markdown
Raw Normal View History

2021-05-09 15:37:29 +08:00
# WebSocket coroutine client
2019-07-02 02:13:55 +08:00
2021-05-09 15:37:29 +08:00
Hyperf provides an encapsulation of WebSocket Client. The WebSocket Server could be accessed through [hyperf/websocket-client](https://github.com/hyperf/websocket-client) component.
2019-07-02 02:13:55 +08:00
2019-12-12 16:24:04 +08:00
## Installation
2019-07-02 02:13:55 +08:00
```bash
composer require hyperf/websocket-client
```
2021-05-09 15:37:29 +08:00
## Usage
2019-07-02 02:13:55 +08:00
2021-05-09 15:37:29 +08:00
`Hyperf\WebSocketClient\ClientFactory` is provided to create `Hyperf\WebSocketClient\Client` objects.
2019-07-02 02:13:55 +08:00
```php
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
2019-07-04 10:03:03 +08:00
use Hyperf\WebSocketClient\ClientFactory;
2019-07-04 10:07:54 +08:00
use Hyperf\WebSocketClient\Frame;
2019-07-02 02:13:55 +08:00
2019-07-04 10:03:03 +08:00
class IndexController
2019-07-02 02:13:55 +08:00
{
#[Inject]
protected ClientFactory $clientFactory;
2019-07-02 02:13:55 +08:00
public function index()
{
2021-05-09 15:37:29 +08:00
// The address of the peer service. If there is no prefix like ws:// or wss://, then the ws:// would be used as default.
2019-07-02 02:13:55 +08:00
$host = '127.0.0.1:9502';
2021-05-09 15:37:29 +08:00
// Create Client object through ClientFactory. Short-lived objects will be created.
2019-07-02 02:13:55 +08:00
$client = $this->clientFactory->create($host);
2021-05-09 15:37:29 +08:00
// Send a message to the WebSocket server
$client->push('Use WebSocket Client to send data in HttpServer.');
// Get a response from the server. The server should use 'push()' to send messages to fd of the client, only in this way, can the response be received.
// A Frame object is taken as an example in following with 2 seconds timeout.
2019-07-04 10:07:54 +08:00
/** @var Frame $msg */
2019-07-04 10:03:03 +08:00
$msg = $client->recv(2);
2021-05-09 15:37:29 +08:00
// Get text data: $res_msg->data
2019-07-04 10:03:03 +08:00
return $msg->data;
2019-07-02 02:13:55 +08:00
}
}
```
2021-05-09 15:37:29 +08:00
## Close the $autoClose
2019-07-02 02:13:55 +08:00
2021-05-09 15:37:29 +08:00
By default, the created `Client` object will be closed by `defer`. If it is not wished, the auto-close could be closed by setting the `$autoClose` as `false` when a `Client` is in instantiating.
2019-07-02 02:13:55 +08:00
```php
$autoClose = false;
2019-07-04 10:03:03 +08:00
$client = $clientFactory->create($host, $autoClose);
```