Hyperf provides an encapsulation of WebSocket Server. A WebSocket application can be quickly built based on [hyperf/websocket-server](https://github.com/hyperf/websocket-server).
> So far, only the config file way is supported. The annotation way will come soon.
In the `config/routes.php` file, add the router configuration of the Server of corresponding `ws`, where `ws` is the `name` of the WebSocket Server in `config/autoload/server.php`.
In the `config/autoload/middlewares.php` file, add the middleware configuration of the Server of corresponding `ws`, where `ws` is the `name` of the WebSocket Server in `config/autoload/server.php`.
Start the Server, then you can see a WebSocket Server is started and listen to port of 9502. You can then use any WebSocket Client to communicate with this WebSocket Server.
!> When we listen the 9501 of the HTTP Server and the 9502 of the WebSocket Server at the same time, the WebSocket Client can connect to the WebSocket Server through the two ports 9501 and 9502, that is, connecting to `ws://0.0.0.0:9501` and `ws:/ /0.0.0.0:9502` both works.
Due to the `Swoole\WebSocket\Server` inherits from `Swoole\Http\Server`, you can use HTTP to perform all WebSocket pushes. For more details, please refer the callback of `onRequest` in [Swoole Doc](https://wiki.swoole.com/#/websocket_server?id=websocketserver)
If you need to close it, you can add the `open_websocket_protocol` configuration item to the `http` service in `config/autoload/server.php` file.
Callbacks for onOpen, onMessage, and onClose of WebSocket are not triggered in the same coroutine, so that they cannot directly use the stored information of context. **Connected Context** is provided by WebSocket Server component, and API is same as coroutine context's.
```php
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\WebSocketServer\Context;
use Swoole\Http\Request;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server as WebSocketServer;
class WebSocketController implements OnMessageInterface, OnOpenInterface
{
public function onMessage($server, Frame $frame): void
When you want to close `WebSocket` connection in `HTTP` service, you can used`Hyperf\WebSocketServer\Sender`.
`Sender` will check if `fd` is carried by the current `Worker`, if so, then directly send the message, otherwise, send message to all other `Worker` through `PipeMessage`. Other `Worker`s will do the same as mentioned above.