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.


composer require hyperf/websocket-server

Configure Server

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


'servers' => [
        'name' => 'ws',
        'type' => Server::SERVER_WEBSOCKET,
        'host' => '',
        '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.


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

Create corresponding controller


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

    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
[INFO] HTTP Server listening at

WebSocket orchestration client

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


composer require hyperf/websocket-client


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


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 = '';
        // 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


$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