关于libevent的大致介绍,可以参考博文 libevent学习笔记
此处使用上述方法实现一个简单的服务器与客户端程序:
server.cpp:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <event.h>
#include <sys/socket.h>
#include <sys/types.h>
using namespace std;
//事件base
struct event_base *base;
void onWrite(int sock, short iEvent, void* arg){
char* buf = (char*)arg;
send(sock, buf, strlen(buf), 0);
//delete buf;
}
void onRead(int iCliFd, short iEvent, void* arg){
int iLen;
char buf[1024];
iLen = recv(iCliFd, buf, sizeof(buf), 0);
if(iLen <= 0){
cout << "client close" << endl;
//连接结束(=0)或连接错误(<0),将事件删除并释放内存空间
struct event *pEvRead = (struct event*)arg;
event_del(pEvRead);
delete pEvRead;
close(iCliFd);
return;
}
buf[iLen] = 0;
cout << "Client Info:" &