360 evpp现代化C++11高性能TCP UDP HTTP网络库
2019独角兽企业重金招聘Python工程师标准>>>
1
安装方法,源码包有说明:https://github.com/Qihoo360/evpp
----------------------------------------------------------------------------------------------------------------
2
tcp回声服务器(官方示例)
#include <evpp/tcp_server.h>
#include <evpp/buffer.h>
#include <evpp/tcp_conn.h>#ifdef _WIN32
#include "../../winmain-inl.h"
#endifvoid OnMessage(const evpp::TCPConnPtr& conn,evpp::Buffer* msg) {std::string s = msg->NextAllString();LOG_INFO << "Received a message [" << s << "]";conn->Send(s);if (s == "quit" || s == "exit") {conn->Close();}
}void OnConnection(const evpp::TCPConnPtr& conn) {if (conn->IsConnected()) {LOG_INFO << "Accept a new connection from " << conn->remote_addr();} else {LOG_INFO << "Disconnected from " << conn->remote_addr();}
}int main(int argc, char* argv[]) {std::string port = "9099";if (argc == 2) {port = argv[1];}std::string addr = std::string("0.0.0.0:") + port;evpp::EventLoop loop;evpp::TCPServer server(&loop, addr, "TCPEcho", 0);server.SetMessageCallback(&OnMessage);server.SetConnectionCallback(&OnConnection);server.Init();server.Start();loop.Run();return 0;
}
----------------------------------------------------------------------------------------------------------------
3
evpp::TCPServer类(主要)
#include <evpp/tcp_server.h>
#pragma once#include "evpp/inner_pre.h"
#include "evpp/event_loop.h"
#include "evpp/event_loop_thread_pool.h"
#include "evpp/tcp_callbacks.h"#include "evpp/thread_dispatch_policy.h"
#include "evpp/server_status.h"#include <map>namespace evpp {class Listener;// We can use this class to create a TCP server.
// The typical usage is :
// 1. Create a TCPServer object
// 2. Set the message callback and connection callback
// 3. Call TCPServer::Init()
// 4. Call TCPServer::Start()
// 5. Process TCP client connections and messages in callbacks
// 6. At last call Server::Stop() to stop the whole server
//
// The examples code is as bellow:
// <code>
// std::string addr = "0.0.0.0:9099";
// int thread_num = 4;
// evpp::EventLoop loop;
// evpp::TCPServer server(&loop, addr, "TCPEchoServer", thread_num);
// server.SetMessageCallback([](const evpp::TCPConnPtr& conn,
// evpp::Buffer* msg) {
// // Do something with the received message
// conn->Send(msg); // At here, we just send the received message back.
// });
// server.SetConnectionCallback([](const evpp::TCPConnPtr& conn) {
// if (conn->IsConnected()) {
// LOG_INFO << "A new connection from " << conn->remote_addr();
// } else {
// LOG_INFO << "Lost the connection from " << conn->remote_addr();
// }
// });
// server.Init();
// server.Start();
// loop.Run();
// </code>
//
class EVPP_EXPORT TCPServer : public ThreadDispatchPolicy, public ServerStatus {
public:typedef std::function<void()> DoneCallback;// @brief The constructor of a TCPServer.// @param loop -// @param listen_addr - The listening address with "ip:port" format// @param name - The name of this object// @param thread_num - The working thread countTCPServer(EventLoop* loop,const std::string& listen_addr/*ip:port*/,const std::string& name,uint32_t thread_num);~TCPServer();// @brief Do the initialization works here.// It will create a nonblocking TCP socket, and bind with the give address// then listen on it. If there is anything wrong it will return false.// @return bool - True if anything goes wellbool Init();// @brief Start the TCP server and we can accept new connections now.// @return bool - True if anything goes wellbool Start();// @brief Stop the TCP server// @param cb - the callback cb will be invoked when// the TCP server is totally stoppedvoid Stop(DoneCallback cb = DoneCallback());// @brief Reinitialize some data fields after a forkvoid AfterFork();public:// Set a connection event relative callback when the TCPServer// receives a new connection or an exist connection breaks down.// When these two events happened, the value of the parameter in the callback is:// 1. Received a new connection : TCPConn::IsConnected() == true// 2. An exist connection broken down : TCPConn::IsDisconnecting() == truevoid SetConnectionCallback(const ConnectionCallback& cb) {conn_fn_ = cb;}// Set the message callback to handle the messages from remote clientvoid SetMessageCallback(MessageCallback cb) {msg_fn_ = cb;}public:const std::string& listen_addr() const {return listen_addr_;}
private:void StopThreadPool();void StopInLoop(DoneCallback on_stopped_cb);void RemoveConnection(const TCPConnPtr& conn);void HandleNewConn(evpp_socket_t sockfd, const std::string& remote_addr/*ip:port*/, const struct sockaddr_in* raddr);EventLoop* GetNextLoop(const struct sockaddr_in* raddr);
private:EventLoop* loop_; // the listening loopconst std::string listen_addr_; // ip:portconst std::string name_;std::unique_ptr<Listener> listener_;std::shared_ptr<EventLoopThreadPool> tpool_;ConnectionCallback conn_fn_;MessageCallback msg_fn_;DoneCallback stopped_cb_;// always in the listening loop threaduint64_t next_conn_id_ = 0;typedef std::map<uint64_t/*the id of the connection*/, TCPConnPtr> ConnectionMap;ConnectionMap connections_;
};
}
----------------------------------------------------------------------------------------------------------------
4
std::function回调类型
part3中的两个evpp::TCPServer类的成员函数(设置回调函数)
void SetConnectionCallback(const ConnectionCallback& cb)
void SetMessageCallback(MessageCallback cb)
其回调类型在源码 #include "evpp/tcp_callbacks.h"
#pragma once#include "evpp/inner_pre.h"namespace evpp {
class Buffer;
class TCPConn;typedef std::shared_ptr<TCPConn> TCPConnPtr;
typedef std::function<void()> TimerCallback;// When a connection established, broken down, connecting failed, this callback will be called
// This is called from a work-thread this is not the listening thread probably
typedef std::function<void(const TCPConnPtr&)> ConnectionCallback;typedef std::function<void(const TCPConnPtr&)> CloseCallback;
typedef std::function<void(const TCPConnPtr&)> WriteCompleteCallback;
typedef std::function<void(const TCPConnPtr&, size_t)> HighWaterMarkCallback;typedef std::function<void(const TCPConnPtr&, Buffer*)> MessageCallback;namespace internal {
inline void DefaultConnectionCallback(const TCPConnPtr&) {}
inline void DefaultMessageCallback(const TCPConnPtr&, Buffer*) {}
}}
----------------------------------------------------------------------------------------------------------------
5
evpp::EventLoop类
evpp::EventLoop类是IO事件的驱动内核。这个类是event_base类的包装器,但不仅仅是一个包装器。它通过简单的方式,运行IO事件驱动循环。一个线程一个循环。
在evpp::TCPServer对象设置完回调函数及调用Init()、Start()之后,必须执行IO事件线程Run(),如part2示例。
----------------------------------------------------------------------------------------------------------------
6
以上是evpp tcp网络库的大致用法。udp、http用法参照源码。
evpp语法采用C++11的特性,大量使用std::string,而不是char*独占天;使用std::stringstream,而不是sprintf;易读的Lambda,而不是函数指针等等。满满的C++11诚意。http库更是可以弥补C++开发http服务器效率低的问题。膜拜360大佬们!
转载于:https://my.oschina.net/feistel/blog/3001279
360 evpp现代化C++11高性能TCP UDP HTTP网络库相关推荐
- 高性能 TCP UDP 通信框架 HP-Socket v3.2.3
HP-Socket 是一套通用的高性能 TCP/UDP 通信框架,包含服务端组件.客户端组件和 Agent 组件,广泛适用于各种不同应用场景的 TCP/UDP 通信系统,提供 C/C++.C#.Del ...
- Linux Kernel TCP/IP Stack — Socket Layer — TCP/UDP Socket 网络编程
目录 文章目录 目录 TCP/UDP Socket 逻辑架构 创建 Socket 绑定 Socket 请求建立 Socket 连接 监听 Socket 接受请求 关闭连接 数据的发送和接收 send ...
- 高性能udp服务器架构,优秀的国产高性能TCP/UDP/HTTP开源网络通信框架——HP
介绍 HP-Socket是国人开发的一套高性能的TCP/UDP/HTTP网络通信框架,包含了服务端.客户端以及Agent组件,可用于各种不同应用场景的通信系统,并且提供了C/C++.C#.Delphi ...
- socket通信项目开源c语言,优秀的国产高性能TCP/UDP/HTTP开源网络通信框架——HP-Socket...
介绍 HP-Socket是国人开发的一套高性能的TCP/UDP/HTTP网络通信框架,包含了服务端.客户端以及Agent组件,可用于各种不同应用场景的通信系统,并且提供了C/C++.C#.Delphi ...
- 三十天学不会TCP,UDP/IP网络编程-IP头格式祥述
我又来了,这篇文章还是来做(da)推(guang)介(gao)我自己的!俗话说事不过三,我觉得我下次得换个说法了,不然估计要被厌恶了,但是我是好心呐,一定要相信我纯洁的眼神.由于这两年接触到了比较多的 ...
- TCP UDP之网络编程及数据库入门
一:网络编程三要素+UDP协议讲解 1.1 1.网络通信介绍 2.tcp/ip 3.udp/ip 1.2 Socket通信 * 网络编程三要素: ip: 一个计算的标示(找到这个计算机) 端口: 应用 ...
- 三十天学不会TCP,UDP/IP网络编程-TraceRoute的哲学
新年快乐,继续来部分粘贴复制我的这一系列文章啦,如果对和程序员有关的计算机网络知识,和对计算机网络方面的编程有兴趣,欢迎去gitbook(https://rogerzhu.gitbooks.io/-t ...
- 三十天学不会TCP,UDP/IP网络编程 - RST的用法
不知不觉也写了这么多了,继续我的自己的推广大业~完整版可以去gitbook(https://rogerzhu.gitbooks.io/-tcp-udp-ip/content/)看到. 如果对和程序员有 ...
- libgo高性能网络服务器,【开源】gnet: 一个轻量级且高性能的 Golang 网络库
![](https://ask.qcloudimg.com/http-save/1303222/sipe2g9n9h.png) # Github 主页 [https://github.com/panj ...
最新文章
- java性能分析 linux,linux 系统性能分析
- Python代码发现链表中的环并输出环中的第一个元素
- python互相转换组合_Python基本类型的连接组合和互相转换方式(13种)
- sqlserver 实现数据库全文检索
- 12.04 深圳站 | Serverless Developer Meetup 开放报名
- 【学生信息管理系统】——优化篇(一)
- 153. 寻找旋转排序数组中的最小值---LeetCode---JAVA
- VS2010与.NET4系列 16.ASP.NET 4 Web Forms 更加干净的HTML标记
- 广告传媒实际税负怎么计算_建材销售类营业额3亿,缺进项致税负高?成立4家独资企业节税90%...
- 计算机游戏程序启动错误及其解决方法汇总
- win7查看远程连接了计算机名,win7怎么查看远程连接信息 win7远程连接设置教程...
- python+大数据之数据可视化完整版
- Win7虚拟机无法连接网络怎么办?已解决!!
- 数模新版视频课程第11讲.时间序列分析
- SpringCloud微服务实战——搭建企业级开发框架(二十七):集成多数据源+Seata分布式事务+读写分离+分库分表
- Nacos 1.1.0发布,支持灰度配置和地址服务器模式
- matlab后退和前进的快捷键,MATLAB 常用操作命令和快捷键
- 推荐5个神仙软件,个个让你爱不释手
- axios接口报错-参数类型错误解决
- Android Ripple的详解