以下代码在vs 2010编译通过,使用的libevent版本是:libevent-2.0.22,win7环境测试通过。
服务器实现:
1 流程图:
2 代码:
// my_telnet.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string.h> #include <errno.h> #include <stdio.h> #include <signal.h> #ifndef WIN32 #include <netinet/in.h> # ifdef _XOPEN_SOURCE_EXTENDED # include <arpa/inet.h> # endif #include <sys/socket.h> #endif #include "event2/bufferevent.h" #include "event2/buffer.h" #include "event2/listener.h" #include "event2/util.h" #include "event2/event.h" #include "event2/util.h" #include <WinSock2.h> //#include "MySimpleLog.h" static const int PORT = 9995; //读取一行输入并返回 static void conn_readcb(struct bufferevent *bev, void *user_data) { //MY_SIMPLE_LOG_DEBUG("conn_readcb! "); //只有读到一行完整行才进行处理 所以这里需要检查缓冲区是否存在换行符 //如果存在才往下走 struct evbuffer *input = bufferevent_get_input(bev); struct evbuffer_ptr ptrInput; if ((ptrInput = evbuffer_search(input , " ", 1, NULL)).pos == -1) { return; } char line[1024] = {0}; int nRead = 0; //已读取字节数 int nExpect = ptrInput.pos + 1; //期望读取的字节数 //把这一行读取出来(如果大于1024则需要分次读取) while (nRead < nExpect) { int nLeft = nExpect - nRead; int nReadOnce = min(nLeft, sizeof(line) - 1); int n = bufferevent_read(bev, line, nReadOnce); if (n <= 0) { //MY_SIMPLE_LOG_ERROR("expect to read %d bytes,but get %d.", nReadOnce, n); break; } line[n] = '