1. Go to this page and download the library: Download mix/websocket 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/ */
mix / websocket example snippets
$upgrader = new Mix\WebSocket\Upgrader();
$vega = new Mix\Vega\Engine();
$vega->handle('/websocket', function (Mix\Vega\Context $ctx) use ($upgrader) {
// 升级连接
$conn = $upgrader->upgrade($ctx->request, $ctx->response);
// 接收消息
$in = $conn->readMessage();
var_dump($in->data);
// 发送消息
$out = new Swoole\WebSocket\Frame();
$out->data = sprintf('hello, %s', $in->data);
$conn->send($out);
$conn->close();
})->methods('GET');
Swoole\Coroutine\run(function () {
$upgrader = new Mix\WebSocket\Upgrader();
$server = new Swoole\Coroutine\Http\Server('0.0.0.0', 9502, false);
$server->handle('/websocket', function (Swoole\Http\Request $request, Swoole\Http\Response $response) use ($upgrader) {
// 升级连接
$conn = $upgrader->upgradeRaw($request, $response);
// ...
});
$server->start();
});