PHP code example of kode / messaging
1. Go to this page and download the library: Download kode/messaging 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/ */
kode / messaging example snippets
Kode\Messaging\Messaging;
Messaging::server('ws://0.0.0.0:8080')
->on('connection.open', fn($c) => $c->send('welcome'))
->on('message.received', fn($c, $m) => $c->send("echo: {$m->payload()}"))
->start();
Messaging::server('sse://0.0.0.0:8081')
->interval(1000)
->on('interval', fn($c) => $c->send(['event' => 'tick', 'data' => time()]))
->start();
Messaging::client('mqtt://broker.example.com:1883')
->withClientId('device-001')
->subscribe('sensors/+/temperature', function ($topic, $payload) {
echo "[$topic] $payload\n";
})
->connect()
->loop();
Messaging::server('mqtt://0.0.0.0:1883')
->on('connection.open', fn($c) => log_connect($c))
->on('message.received', function ($c, $m) {
$topic = $m->topic();
$payload = $m->payload();
echo "[mqtt] topic={$topic} payload={$payload}\n";
})
->start();
$client = Messaging::client('nats://broker:4222');
$client->subscribe('orders.*', function ($subject, $payload) {
echo "[$subject] $payload\n";
});
$client->connect();
$client->publish('orders.created', json_encode(['id' => 1]));
$client = Messaging::client('stomp://broker:61613');
$client->subscribe('/queue/orders', function ($data) {
echo $data['body'] . "\n";
});
$client->connect();
$client->send('/queue/orders', 'hello');
$client = Messaging::client('grpc://api.example.com:50051');
$response = $client->call('/helloworld.Greeter/SayHello', $reqPayload);
$client = Messaging::client('webtransport://example.com:4433');
$conn = $client->connect();
$conn->sendBidirectional('hello');
$conn->sendDatagram('ping', reliable: false);
Messaging::server('rtmp://0.0.0.0:1935')
->on('message.received', fn($c, $m) => log_rtmp($m))
->start();
// 设备端:裸 MQTT(高效、省资源)
Messaging::server('mqtt://0.0.0.0:1883')
->on('message.received', fn($c, $m) => handle_device($m))
->start();
// 用户端:MQTT over WebSocket(穿越防火墙)
Messaging::server('mqtt+ws://0.0.0.0:8083')
->on('message.received', fn($c, $m) => handle_app($m))
->start();
// 集群模式:百万设备连接(多节点通过 Redis 总线同步)
Messaging::server('mqtt://0.0.0.0:1883')
->withCluster(true, 'node-1') // 启用 Redis 跨节点消息路由
->start();
// 手动指定传输层
Messaging::configure(['transport' => 'swoole']);
// 或运行时检测
use Kode\Messaging\Kode;
echo Kode::runtime(); // 'swoole' | 'swow' | 'workerman' | 'plain'
use Kode\Messaging\Kode;
// JSON 校验(8.3 基线直接用 json_validate)
Kode::jsonValidate('{"ok":true}'); // bool
// 安全随机(8.3 基线直接用 Randomizer)
Kode::randomBytes(16); // string
// 运行时环境检测
Kode::runtime(); // 'swoole' | 'swow' | 'workerman' | 'plain'
Kode::inCoroutine(); // bool