djfm / socket-rpc
此包的最新版本(1.0.0)没有可用的许可证信息。
1.0.0
2015-02-10 14:39 UTC
Requires (Dev)
- phpunit/phpunit: ~4.4
This package is not auto-updated.
Last update: 2024-09-28 16:05:08 UTC
README
SocketRPC提供了一个方便的方法,在CLI PHP服务器和多个客户端之间共享结构化数据。服务器是异步的,灵感来源于reactphp在GitHub上的优秀工作。
想象一下HTTP,但没有结构。它很方便。没有POST,没有GET,只有JSON数据和客户端是否需要回复的概念。其余的协议由您随意定义。
安装
在packagist上,只需将 "djfm/socket-rpc": "dev-master"
添加到您的composer.json中。
披露
这是一个早期版本,不要用它做任何事情太严肃。我需要一个跨平台的方式来实现像msg_queue
这样的功能,用于PHP中的IPC通信,所以我创建了这个东西。
示例
下面是一个示例服务器
<?php use djfm\SocketRPC\Server; $server = new Server(); $server->bind(1337); echo sprintf("Server ready to accept connections on `%s`.\n", $server->getAddress()); $server->on('connection', function ($clientId) { echo "Welcome, client #$clientId!\n"; })->on('disconnected', function ($clientId) { echo "Bye, client #$clientId!\n"; })->on('send', function ($data, $clientId) { // client sends data to us, but does not expect a reply, // think logs, monitoring... var_dump($data); })->on('query', function ($query, $respond, $clientId) { // client sends us something, and wants a response var_dump($query); $respond(42); }); // this loops never returns, set things up before :) $server->run();
这里是一个客户端
<?php use djfm\SocketRPC\Client; $client = new Client(); $client->connect("tcp://127.0.0.1:1337"); // We just need to tell something to the server, don't wait for a reply $client->send('hello'); // This is important, expect a reply $response = $client->query('41 + 1 ?'); echo "Response: $response\n";
示例可以在本repo的examples
文件夹中找到。
设计
服务器端是异步的,因此它可以平滑地处理许多并发连接。
但在客户端,请求是同步的,因为这是PHP,异步范式很快就会变得繁琐。
您可以通过网络传输任何可序列化为JSON的有效负载。如果您需要发送二进制数据,请先使用base64_encode
。
测试
要检查您的平台上的所有内容是否正常,请运行
phpunit tests