zerobus希望进一步抽象应用和进程间通信,通过配置能灵活设置应用和进程间通信(灵活选择TCP,UDP,共享内存进行通信)方式,方便网络程序开发和部署。
在zerobus中通信双方(进程或跨机的应用)的抽象叫做通道(channel),它通过zeromq高性能消息队列来实现通信通道(channel)。
(1)进程或应该通信配置如下
<?xml version="1.0" encoding="UTF-8"?> <root> <!-- SERVER_1 = 1, SERVER_2 = 2 --> <!--服务器id实例id:例如10001表示服务器1实例1 -->
<!--服务器2实例1和服务器1实例1,通过tcp通信 -->
<channel type="0" connector_id="20001" acceptor_id="10001" url="tcp://127.0.0.1:5561" bufsize="1000" />
<!--服务器2实例2和服务器1实例2,通过ipc通信 -->
<channel type="0" connector_id="20002" acceptor_id="10002" url="ipc:///tmp/20001_10001" bufsize="1000" />
</root>
(2)基于zerobus的echo客户端示例
#include "Channel.hpp" #include "ZBus.hpp" #include "Error.hpp" #include "Reactor.hpp" #include <cstdio> #include <cstring> using namespace zerobus::zmqbind; using namespace zerobus::framework;
//IO处理器 class ReactorHandler: public IOHandler { public: int OnReceiveMessage(Channel* channel) { memset(_data, 0, sizeof(_data)); if (channel != NULL) { int len = sizeof(_data); int ret = channel->Recv(_data, len); if (ret > 0) { printf("server resp : iRet %d, %s\n", ret, _data); } return 0; } return -1; } private: char _data[1024*1024]; }; int main() {
ReactorHandler handler;
//初始化zerobus
Reactor reactor = ZBus::Instance().InitZBus(20001, "channel_temp.xml", handler);
if (reactor == NULL)
{
printf("register channel failed\n");
return -1;
}
Channel* pchannel = ZBus::Instance().GetChannel(20001, 10001);
if (pchannel == NULL)
{
printf("get channel failed\n");
return -1;
}
char str[12] = "hello world";
pchannel->Send(str, sizeof(str));
int i = 1; while (i) {
//事件循环 reactor.EventLoop(1000); i--; } return 0; }
(3)基于zerobus的echo服务端示例
#include "Channel.hpp" #include "ZBus.hpp" #include "Error.hpp" #include "Reactor.hpp" #include <cstdio> #include <cstring> using namespace zerobus::zmqbind; using namespace zerobus::framework;class ReactorHandler: public IOHandler { public:
int OnReceiveMessage(Channel* channel) { memset(_data, 0, sizeof(_data)); if (channel != NULL) { int len = sizeof(_data); int ret = channel->Recv(_data, len); if (ret > 0) {//发送收到的数据到客户端 channel->Send(_data, len); } return 0; } return -1; } private:char _data[1024*1024]; };
int main() { ReactorHandler handler; //初始化zerobus Reactor reactor = ZBus::Instance().InitZBus(10001, "channel_temp.xml", handler); if (reactor == NULL) { printf("register channel failed\n");
return -1; } //事件循环 while (1) { reactor.EventLoop(1000); } return 0; }
从示例代码,可以看出zerobus能使开发者不需要关注网络通信,把重心放到业务逻辑处理上去
zerobus下一步将会加入RPC 功能,了解详细实现,请猛击https://github.com/weiffun/zerobus