Hyperf / websocket server / client and server real-time two-way data transmission

Keywords: Programming PHP github

WebSocket service

WebSocket is a kind of communication protocol, which can carry out full duplex communication on a single TCP connection. WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In WebSocket API, browser and server only need to complete one handshake, and they can establish persistent connection and two-way data transmission.

Hyperf provides encapsulation of WebSocket Server based on hyperf/websocket-server Component to quickly build a WebSocket application.

install

composer require hyperf/websocket-server

Configure Server

Modify config/autoload/server.php to add the following configuration.

<?php

'servers' => [
    [
        'name' => 'ws',
        'type' => Server::SERVER_WEBSOCKET,
        'host' => '0.0.0.0',
        'port' => 9502,
        'sock_type' => SWOOLE_SOCK_TCP,
        'callbacks' => [
            SwooleEvent::ON_HAND_SHAKE => [Hyperf\WebSocketServer\Server::class, 'onHandShake'],
            SwooleEvent::ON_MESSAGE => [Hyperf\WebSocketServer\Server::class, 'onMessage'],
            SwooleEvent::ON_CLOSE => [Hyperf\WebSocketServer\Server::class, 'onClose'],
        ],
    ],
],

Configuration routing

Currently, only the profile mode is supported to configure routing, and annotation mode will be provided later.

Add the routing configuration of the corresponding ws Server in the config/routes.php file. The ws value here depends on the WebSocket Server name value configured in config/autoload/server.php.

<?php

Router::addServer('ws', function () {
    Router::get('/', 'App\Controller\WebSocketController');
});

Create corresponding controller

<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Swoole\Http\Request;
use Swoole\Server;
use Swoole\Websocket\Frame;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage(Server $server, Frame $frame): void
    {
        $server->push($frame->fd, 'Recv: ' . $frame->data);
    }

    public function onClose(Server $server, int $fd, int $reactorId): void
    {
        var_dump('closed');
    }

    public function onOpen(Server $server, Request $request): void
    {
        $server->push($request->fd, 'Opened');
    }
}

After starting the Server, you can see that a WebSocket Server has been started and monitored on port 9502. At this time, you can connect and transfer data through various websocket clients.

$ php bin/hyperf.php start

[INFO] Worker#0 started.
[INFO] WebSocket Server listening at 0.0.0.0:9502
[INFO] HTTP Server listening at 0.0.0.0:9501

WebSocket orchestration client

Hyperf provides encapsulation of WebSocket Client based on hyperf/websocket-client Components access WebSocket Server;

install

composer require hyperf/websocket-client

Use

The component provides a Hyperf\WebSocketClient\ClientFactory to create a client object, Hyperf\WebSocketClient\Client. We can directly demonstrate it by code:

<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;

class IndexController extends Controller
{

    /**
     * @Inject()
     * @var \Hyperf\WebSocketClient\ClientFactory
     */
    protected $clientFactory;

    public function index()
    {
        // The address of the peer-to-peer service. If ws: / / or wss: / / prefix is not provided, ws://
        $host = '127.0.0.1:9502';
        // Create the Client object through ClientFactory, and the created object is a short life cycle object
        $client = $this->clientFactory->create($host);
    }
}

Auto close connection switch

By default, the created Client object will be automatically connected through defer. If you do not want to close automatically, you can pass the second parameter $autoClose to false when creating the Client object

<?php

$autoClose = false;
$clientFactory->create($host, $autoClose);

Official website and communication

Github < point Star to support us
Hyperf official website

Related links

Posted by rawky1976 on Tue, 10 Mar 2020 21:06:02 -0700