服务端
<?php
$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
echo "server: handshake success with fd{$request->fd}\n";
});
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "this is server");
});
$server->on('close', function ($server, $fd) {
echo "client {$fd} closed\n";
});
$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
global $server;
foreach ($server->connections as $fd) {
if ($server->isEstablished($fd)) {
$server->push($fd, $request->get['message']);
}
}
$response->end('success');
return;
});
$server->start();
客户端连接
try {
$client = new \GuzzleHttp\Client();
$client->request('GET', 'http://127.0.0.1:9501', ['query' => [
'message' => '有新品上架了',
]]);
} catch (Exception $e) {
}