1. Go to this page and download the library: Download mix/websocket-skeleton library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\Controller;
use App\Container\Upgrader;
use App\Service\Session;
use Mix\Vega\Context;
class WebSocket
{
/**
* @param Context $ctx
*/
public function index(Context $ctx)
{
$conn = Upgrader::instance()->upgrade($ctx->request, $ctx->response);
$session = new Session($conn);
$session->start();
}
}
namespace App\Service;
use App\Handler\Hello;
use Mix\WebSocket\Connection;
use Swoole\Coroutine\Channel;
class Session
{
/**
* @var Connection
*/
protected $conn;
/**
* @var Channel
*/
protected $writeChan;
/**
* Session constructor.
* @param Connection $conn
*/
public function __construct(Connection $conn)
{
$this->conn = $conn;
$this->writeChan = new Channel(10);
}
/**
* @param string $data
*/
public function send(string $data): void
{
$this->writeChan->push($data);
}
public function start(): void
{
// 接收消息
go(function () {
while (true) {
$frame = $this->conn->recv();
$message = $frame->data;
(new Hello($this))->index($message);
}
});
// 发送消息
go(function () {
while (true) {
$data = $this->writeChan->pop();
if (!$data) {
return;
}
$frame = new \Swoole\WebSocket\Frame();
$frame->data = $data;
$frame->opcode = WEBSOCKET_OPCODE_TEXT; // or WEBSOCKET_OPCODE_BINARY
$this->conn->send($frame);
}
});
}
}