融合libevent和protobuf
写了一个简单的例子,把libevent中的bufferevent网络收发服务和protobuf里面的序列反序列结合起来。
protobuf文件message.proto:
message PMessage {
required int32 id = 1;
optional int32 num = 2;
optional string str = 3;
}
生成接口命令:
protoc -I=proto --cpp_out=src proto/message.proto
服务器端 lserver.cc:
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h> #include <stdio.h>
#include <string.h> #include <event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/thread.h> #include "message.pb.h" using namespace std; void listener_cb(evconnlistener *listener, evutil_socket_t fd,
sockaddr *sock, int socklen, void *arg); void socket_read_cb(bufferevent *bev, void *arg); void socket_event_cb(bufferevent *bev, short events, void *arg); int main(int argc, char **argv) {
sockaddr_in sin;
memset(&sin, 0, sizeof(sockaddr_in)); sin.sin_family = AF_INET;
sin.sin_port = htons(8899); event_base *base = event_base_new();
evconnlistener *listener
= evconnlistener_new_bind(base,
listener_cb, base,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE,
10, (sockaddr*)&sin, sizeof(sockaddr_in)); event_base_dispatch(base); evconnlistener_free(listener);
event_base_free(base); } void listener_cb(evconnlistener *listener, evutil_socket_t fd,
sockaddr *sock, int socklen, void *arg) { printf("accept a client %d\n", fd);
event_base *base = (event_base *)arg; bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(bev, socket_read_cb, NULL, socket_event_cb, NULL);
bufferevent_enable(bev, EV_READ|EV_PERSIST); } void socket_read_cb(bufferevent *bev, void *arg) {
char msg[4096];
size_t len = bufferevent_read(bev, msg, sizeof(msg)-1);
msg[len] = '\0'; PMessage pmsg;
pmsg.ParseFromArray((const void*)msg, len); printf("Server read the data:%i, %i, %s\n", pmsg.id(), pmsg.num(), pmsg.str().c_str()); pmsg.set_str("I have read your data.");
string sendbuf;
pmsg.SerializeToString(&sendbuf); bufferevent_write(bev, sendbuf.c_str(), sendbuf.length()); } void socket_event_cb(bufferevent *bev, short events, void *arg) {
if (events & BEV_EVENT_EOF) {
printf("connection close\n");
}
else if (events & BEV_EVENT_ERROR) {
printf("some other error\n");
} bufferevent_free(bev);
}
客户端lclient.cc
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h> #include <stdio.h>
#include <string.h>
#include <stdlib.h> #include <event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/util.h> #include "message.pb.h" using namespace std; void cmd_msg_cb(int fd, short events, void *arg); void server_msg_cb(bufferevent *bev, void *arg); void event_cb(bufferevent *bev, short event, void *arg); static int gid = 1; int main(int argc, char **argv) {
if (argc < 3) {
printf("please input IP and port\n");
return 1;
} event_base *base = event_base_new();
bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); event *ev_cmd = event_new(base, STDIN_FILENO,
EV_READ|EV_PERSIST,
cmd_msg_cb, (void *)bev);
event_add(ev_cmd, NULL); sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
inet_aton(argv[1], &server_addr.sin_addr); bufferevent_socket_connect(bev, (sockaddr*)&server_addr, sizeof(server_addr)); bufferevent_setcb(bev, server_msg_cb, NULL, event_cb, (void*)ev_cmd);
bufferevent_enable(bev, EV_READ|EV_PERSIST); event_base_dispatch(base); printf("Finish\n");
return 0; } void cmd_msg_cb(int fd, short events, void *arg) {
char msg[1024];
int ret = read(fd, msg, sizeof(msg));
if (ret < 0) {
perror("read error.\n");
exit(1);
} // protobuf
PMessage pmsg;
pmsg.set_id(gid++);
pmsg.set_num(rand());
pmsg.set_str(msg); string sendbuf;
pmsg.SerializeToString(&sendbuf); // processing network transfer
bufferevent *bev = (bufferevent *)arg;
bufferevent_write(bev, sendbuf.c_str(), sendbuf.length());
} void server_msg_cb(bufferevent *bev, void *arg) {
char msg[1024]; size_t len = bufferevent_read(bev, msg, sizeof(msg)-1);
msg[len] = '\0'; PMessage pmsg;
pmsg.ParseFromArray((const void*)msg, len); printf("Recv %d, %d, %s from server.\n", pmsg.id(), pmsg.num(), pmsg.str().c_str());
} void event_cb(bufferevent *bev, short eventid, void *arg) {
if (eventid & BEV_EVENT_EOF) {
printf("Connection closed.\n");
}
else if (eventid & BEV_EVENT_ERROR) {
printf("Some other error.\n");
}
else if (eventid & BEV_EVENT_CONNECTED) {
printf("Client has successfully connected.\n");
return;
} bufferevent_free(bev);
event *ev = (event *)arg;
event_free(ev);
}
服务器端和客户端共用的Makefile:
CXX=/opt/compiler/gcc-4.8.2/bin/g++ INCPATH= \
/home/work/.jumbo/include/ DEP_LDFLAGS= \
-L/home/work/.jumbo/lib/ DEP_LDLIBS= \
-levent \
-lprotobuf \
-lpthread TARGET= lserver lclient all : $(TARGET) lserver : lserver.cc message.pb.cc
$(CXX) -o $@ $^ -I$(INCPATH) $(DEP_LDFLAGS) $(DEP_LDLIBS) lclient : lclient.cc message.pb.cc
$(CXX) -o $@ $^ -I$(INCPATH) $(DEP_LDFLAGS) $(DEP_LDLIBS) .PHONY : all clean clean :
rm -rf $(TARGET)
服务器命令及输出:
src]$ ./lserver
accept a client 7
Server read the data:1, 1804289383, aaaaaaaaaaaaaaaaaaaaaaaaa Server read the data:2, 846930886, aa Server read the data:3, 1681692777, bb Server read the data:4, 1714636915, abcdefg Server read the data:5, 1957747793, connection close
accept a client 7
Server read the data:1, 1804289383, 2aa Server read the data:2, 846930886, 2bb Server read the data:3, 1681692777, 111111111111111111111222222222222222222222223333333333333333333333333 Server read the data:4, 1714636915, ^C
客户端命令及输出:
src]$ ./lclient localhost 8899
Client has successfully connected.
aaaaaaaaaaaaaaaaaaaaaaaaa
Recv 1, 1804289383, I have read your data. from server.
aa
Recv 2, 846930886, I have read your data. from server.
bb
Recv 3, 1681692777, I have read your data. from server.
abcdefg
Recv 4, 1714636915, I have read your data. from server. Recv 5, 1957747793, I have read your data. from server.
^C
[src]$ ./lclient localhost 8899
Client has successfully connected.
2aa
Recv 1, 1804289383, I have read your data. from server.
2bb
Recv 2, 846930886, I have read your data. from server.
111111111111111111111222222222222222222222223333333333333333333333333
Recv 3, 1681692777, I have read your data. from server. Recv 4, 1714636915, I have read your data. from server.
Connection closed.
Finish
注意:
1. 先后开了两个客户端。客户端退出,不影响服务器端。但是服务器端退出会让客户端一起退出,因为客户端在收到网络error信号处理的最后,会free掉从命令行读数据的监听event,这样eventbase就不会再有event需要监听了,所以会退出。
2. 开始在命令行输入的时候,在char数组中没有添加'\0',传输时会造成如下错误。
[libprotobuf ERROR google/protobuf/wire_format.cc:1053] String field contains invalid UTF-8 data when serializing a protocol buffer. Use the 'bytes' type if you intend to send raw bytes.
根据读入函数返回的长度,设置'\0'即可避免这个错误。
融合libevent和protobuf的更多相关文章
- RPC的学习 & gprotobuf 和 thrift的比较
参考 http://blog.csdn.net/pi9nc/article/details/17336663 集成libevent,google protobuf的RPC框架 RPC(Remote P ...
- 教你成为全栈工程师(Full Stack Developer) 〇-什么是全栈工程师
作为一个编码12年的工程师老将,讲述整段工程师的往事,顺便把知识都泄露出去,希望读者能少走一些弯路. 这段往事包括:从不会动的静态网页到最流行的网站开发.实现自己的博客网站.在云里雾里的云中搜索.大数 ...
- libevent源码深度剖析
原文地址: http://blog.csdn.net/sparkliang/article/details/4957667 第一章 1,前言 Libevent是一个轻量级的开源高性能网络库,使用者众多 ...
- Libevent浅析
前段时间对Libevent的源码进行了阅读,现整理如下: 介绍 libevent是一个轻量级的开源高性能事件驱动网络库,是一个典型的Reactor模型.其主要特点有事件驱动,高性能,跨平台,统一事件源 ...
- protobuf使用详解
https://blog.csdn.net/skh2015java/article/details/78404235 原文地址:http://blog.csdn.net/lyjshen/article ...
- Libevent学习之SocketPair实现
Libevent设计的精化之一在于把Timer事件.Signal事件和IO事件统一集成在一个Reactor中,以统一的方式去处理这三种不同的事件,更确切的说是把Timer事件和Signal事件融合到了 ...
- libevent源码剖析
libevent是一个使用C语言编写的,轻量级的开源高性能网络库,使用者很多,研究者也很多.由于代码简洁,设计思想简明巧妙,因此很适合用来学习,提升自己C语言的能力. libevent有这样显著地几个 ...
- libevent(了解)
1 前言 Libevent是一个轻量级的开源高性能网络库,使用者众多,研究者更甚,相关文章也不少.写这一系列文章的用意在于,一则分享心得:二则对libevent代码和设计思想做系统的.更深层次的分析, ...
- libevent源码深度剖析九
libevent源码深度剖析九 ——集成定时器事件 张亮 现在再来详细分析libevent中I/O事件和Timer事件的集成,与Signal相比,Timer事件的集成会直观和简单很多.Libevent ...
随机推荐
- QT编译发布程序后报错如缺少dll、“应用程序无法正常启动(0xc000007b)”的可能解决方法
QT编译发布程序后报错如缺少dll.“应用程序无法正常启动(0xc000007b)”的可能解决方法 最近项目要用qt,因为初学没有经验,遇到些小问题常常没什么头绪,也查不到解决方法,刚刚还因为低端错误 ...
- jquery on方法(事件委托)
jquery绑定事件处理函数的方法有好几个,比如:bind(),on(),delegate(),live(). 其中delegate和live都是用on实现的,效果也类似,live好像在1.7版本中已 ...
- centos7.5 ab压力测试安装和swoole压力测试
Apache Benchmark(简称ab) 是Apache安装包中自带的压力测试工具 ,简单易用 1.ab安装 yum -y install httpd-tools 2.ab参数详解,传送门:htt ...
- vue-music 关于搜索历史本地存储
搜索历史 搜索过的关键词 保存在本地存储 localstorage 中,同时多个组件共享搜索历史数据,将数据存到vuex 中,初始值从本地缓存中取得对应key 的值,没有数据默认为空数组 点击搜索关键 ...
- HDU 1231.最大连续子序列-dp+位置标记
最大连续子序列 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...
- NEO4j简单入门
Neo4j是: 一个开源 无Schema 没有SQL 图形数据库 图形数据库也称为图形数据库管理系统或GDBMS. Neo4j的官方网站:http://www.neo4j.org Neo4j的优点 它 ...
- 关于maven工程的几个BUG
换了个新的环境,重新导入的maven工程出现了2个BUG: 1.Could not calculate build plan: Plugin org.apache.maven.plugins:mave ...
- ubuntu16.04系统上安装CAJViewer方法步骤教程详解
下载链接: http://pan.baidu.com/s/1jIqHxLs 或: http://download.csdn.net/detail/arhaiyun/5457947 安装wine1.6: ...
- FastReport.Net使用:[33]高亮显示
1.首先来看下初始报表,很简单很普通. 2.下面对报表改进,90分以上的成绩以绿色显示,60~70分的以橙色斜体显示. 报表设计中选择数据成绩文本框,然后点击工具栏上的“ab突出显示”按钮打开“高亮显 ...
- 【BZOJ 1923】1923: [Sdoi2010]外星千足虫 (高斯消元异或 | BITSET用法)
1923: [Sdoi2010]外星千足虫 Description Input 第一行是两个正整数 N, M. 接下来 M行,按顺序给出 Charles 这M次使用“点足机”的统计结果.每行 包含一个 ...