基于libevent和C++开发的高性能网络服务器介绍以及源码解析(一)

基于libevent开发的高性能网络服务器介绍以及源码解析(一)

源码地址:https://github.com/Qihoo360/evpp

特性

1.现代版的C++11接口
2.非阻塞异步接口都是C++11的functional/bind形式的回调仿函数(不是libevent中的C风格的函数指针)
3.CPU多核友好和线程安全
4.非阻塞纯异步多线程TCP服务器/客户端
5.非阻塞纯异步多线程HTTP服务器/客户端
6.非阻塞纯异步多线程UDP服务器
7.支持多进程模式
8.优秀的跨平台特性和高性能(继承自libevent的优点)

类介绍

Duration : 这是一个时间区间相关的类,自带时间单位信息,参考了Golang项目中的Duration实现。

// Modeled after the time.Duration of Golang project.
#pragma once

#include "evpp/inner_pre.h"

namespace evpp {

// Duration表示两个瞬间之间经过的时间
// int64纳秒计数。表示限制了
// 最大可代表期限约为290年。
class EVPP_EXPORT Duration {
public:
    static const int64_t kNanosecond; // = 1LL
    static const int64_t kMicrosecond;// = 1000
    static const int64_t kMillisecond;// = 1000 * kMicrosecond
    static const int64_t kSecond; // = 1000 * kMillisecond
    static const int64_t kMinute; // = 60 * kSecond
    static const int64_t kHour;   // = 60 * kMinute
public:
    Duration();
    explicit Duration(const struct timeval& t);
    explicit Duration(int64_t nanoseconds);
    explicit Duration(int nanoseconds);
    explicit Duration(double seconds);

    // Nanoseconds returns the duration as an integer nanosecond count.
    int64_t Nanoseconds() const;

    // These methods return double because the dominant
    // use case is for printing a floating point number like 1.5s, and
    // a truncation to integer would make them not useful in those cases.

    // Seconds returns the duration as a floating point number of seconds.
    double Seconds() const;

    double Milliseconds() const;
    double Microseconds() const;
    double Minutes() const;
    double Hours() const;

    struct timeval TimeVal() const;
    void To(struct timeval* t) const;

    bool IsZero() const;
    bool operator< (const Duration& rhs) const;
    bool operator<=(const Duration& rhs) const;
    bool operator> (const Duration& rhs) const;
    bool operator>=(const Duration& rhs) const;
    bool operator==(const Duration& rhs) const;

	//重载运算符,用于实现时间的计算
    Duration operator+=(const Duration& rhs);
    Duration operator-=(const Duration& rhs);
    Duration operator*=(int ns);
    Duration operator/=(int ns);

private:
    int64_t ns_; // nanoseconds
};
} // namespace evpp

#include "duration.inl.h"

这里的设计思路仿照了[Golang]实现的版本来的简单明了,目前C++11中也有类似的实现std::chrono::duration,但稍显复杂,从.h函数可以看出,这个类基本能满足我们的需求。

Buffer: 这是一个缓冲区类,融合了muduo`和[Golang]两个项目中相关类的设计和实现

// Modified from muduo project http://github.com/chenshuo/muduo
// @see https://github.com/chenshuo/muduo/blob/master/muduo/net/Buffer.h and https://github.com/chenshuo/muduo/blob/master/muduo/net/Buffer.cc

#pragma once

#include "evpp/inner_pre.h"
#include "evpp/slice.h"
#include "evpp/sockets.h"

#include <algorithm>

namespace evpp {
class EVPP_EXPORT Buffer {
public:
    static const size_t kCheapPrependSize;
    static const size_t kInitialSize;

    explicit Buffer(size_t initial_size = kInitialSize, size_t reserved_prepend_size = kCheapPrependSize)
        : capacity_(reserved_prepend_size + initial_size)
        , read_index_(reserved_prepend_size)
        , write_index_(reserved_prepend_size)
        , reserved_prepend_size_(reserved_prepend_size) {
        buffer_ = new char[capacity_];
        assert(length() == 0);
        assert(WritableBytes() == initial_size);
        assert(PrependableBytes() == reserved_prepend_size);
    }

    ~Buffer() {
        delete[] buffer_;
        buffer_ = nullptr;
        capacity_ = 0;
    }

    void Swap(Buffer& rhs) {
        std::swap(buffer_, rhs.buffer_);
        std::swap(capacity_, rhs.capacity_);
        std::swap(read_index_, rhs.read_index_);
        std::swap(write_index_, rhs.write_index_);
        std::swap(reserved_prepend_size_, rhs.reserved_prepend_size_);
    }

    // 跳过指定长度的缓存
    void Skip(size_t len) {
        if (len < length()) {
            read_index_ += len;
        } else {
            Reset();
        }
    }

    // Retrieve advances the reading index of the buffer
    // Retrieve it the same as Skip.
    void Retrieve(size_t len) {
        Skip(len);
    }

    // 清空n个字节的缓存
    void Truncate(size_t n) {
        if (n == 0) {
            read_index_ = reserved_prepend_size_;
            write_index_ = reserved_prepend_size_;
        } else if (write_index_ > read_index_ + n) {
            write_index_ = read_index_ + n;
        }
    }


    // 清空所有缓存,效果等同truncate(0)
    void Reset() {
        Truncate(0);
    }

    //将容器的容量增加到一个更大的值
    //或等于len。如果len大于current capacity(),
    //分配新的存储空间,否则该方法不执行任何操作。
    void Reserve(size_t len) {
        if (capacity_ >= len + reserved_prepend_size_) {
            return;
        }

        // TODO add the implementation logic here
        grow(len + reserved_prepend_size_);
    }

    //Read
public:
    // Peek int64_t/int32_t/int16_t/int8_t with network endian
    int64_t ReadInt64() {
        int64_t result = PeekInt64();
        Skip(sizeof result);
        return result;
    }

    int32_t ReadInt32() {
        int32_t result = PeekInt32();
        Skip(sizeof result);
        return result;
    }

    int16_t ReadInt16() {
        int16_t result = PeekInt16();
        Skip(sizeof result);
        return result;
    }

    int8_t ReadInt8() {
        int8_t result = PeekInt8();
        Skip(sizeof result);
        return result;
    }

    Slice ToSlice() const {
        return Slice(data(), length());
    }

    std::string ToString() const {
        return std::string(data(), length());
    }

    void Shrink(size_t reserve) {
        Buffer other(length() + reserve);
        other.Append(ToSlice());
        Swap(other);
    }

    // ReadFromFD reads data from a fd directly into buffer,
    // and return result of readv, errno is saved into saved_errno
    ssize_t ReadFromFD(evpp_socket_t fd, int* saved_errno);

    // Next返回一个切片,包含从缓冲区中取出的下一个n个字节,
    // 如果缓冲区小于n个字节,Next返回整个缓冲区。
    // 切片只在下一次调用读或写方法之前有效。
    Slice Next(size_t len) {
        if (len < length()) {
            Slice result(data(), len);
            read_index_ += len;
            return result;
        }

        return NextAll();
    }

    // NextAll returns a slice containing all the unread portion of the buffer,
    // advancing the buffer as if the bytes had been returned by Read.
    Slice NextAll() {
        Slice result(data(), length());
        Reset();
        return result;
    }

    std::string NextString(size_t len) {
        Slice s = Next(len);
        return std::string(s.data(), s.size());
    }

    std::string NextAllString() {
        Slice s = NextAll();
        return std::string(s.data(), s.size());
    }

    // ReadByte reads and returns the next byte from the buffer.
    // If no byte is available, it returns '\0'.
    char ReadByte() {
        assert(length() >= 1);

        if (length() == 0) {
            return '\0';
        }

        return buffer_[read_index_++];
    }

    // UnreadBytes unreads the last n bytes returned
    // by the most recent read operation.
    void UnreadBytes(size_t n) {
        assert(n < read_index_);
        read_index_ -= n;
    }

    // Peek
public:
    // Peek int64_t/int32_t/int16_t/int8_t with network endian

    int64_t PeekInt64() const {
        assert(length() >= sizeof(int64_t));
        int64_t be64 = 0;
        ::memcpy(&be64, data(), sizeof be64);
        return evppbswap_64(be64);
    }

    int32_t PeekInt32() const {
        assert(length() >= sizeof(int32_t));
        int32_t be32 = 0;
        ::memcpy(&be32, data(), sizeof be32);
        return ntohl(be32);
    }

    int16_t PeekInt16() const {
        assert(length() >= sizeof(int16_t));
        int16_t be16 = 0;
        ::memcpy(&be16, data(), sizeof be16);
        return ntohs(be16);
    }

    int8_t PeekInt8() const {
        assert(length() >= sizeof(int8_t));
        int8_t x = *data();
        return x;
    }

public:
    // data返回length buffer. length()的指针,该指针保存着buffer的未读部分。
    // 该数据只在下一次缓冲区修改前有效(即,
    // 直到下一次调用Read、Write、Reset或Truncate方法)。
    // 至少在下一次缓冲区修改之前,数据会为缓冲区内容起别名,
    // 因此,对slice的立即更改将影响以后读取的结果。
    const char* data() const {
        return buffer_ + read_index_;
    }

    char* WriteBegin() {
        return begin() + write_index_;
    }

    const char* WriteBegin() const {
        return begin() + write_index_;
    }

    // length returns the number of bytes of the unread portion of the buffer
    size_t length() const {
        assert(write_index_ >= read_index_);
        return write_index_ - read_index_;
    }

    // size returns the number of bytes of the unread portion of the buffer.
    // It is the same as length().
    size_t size() const {
        return length();
    }

    // capacity returns the capacity of the buffer's underlying byte slice, that is, the
    // total space allocated for the buffer's data.
    size_t capacity() const {
        return capacity_;
    }

    size_t WritableBytes() const {
        assert(capacity_ >= write_index_);
        return capacity_ - write_index_;
    }

    size_t PrependableBytes() const {
        return read_index_;
    }

    // Helpers
public:
    const char* FindCRLF() const {
        const char* crlf = std::search(data(), WriteBegin(), kCRLF, kCRLF + 2);
        return crlf == WriteBegin() ? nullptr : crlf;
    }

    const char* FindCRLF(const char* start) const {
        assert(data() <= start);
        assert(start <= WriteBegin());
        const char* crlf = std::search(start, WriteBegin(), kCRLF, kCRLF + 2);
        return crlf == WriteBegin() ? nullptr : crlf;
    }

    const char* FindEOL() const {
        const void* eol = memchr(data(), '\n', length());
        return static_cast<const char*>(eol);
    }

    const char* FindEOL(const char* start) const {
        assert(data() <= start);
        assert(start <= WriteBegin());
        const void* eol = memchr(start, '\n', WriteBegin() - start);
        return static_cast<const char*>(eol);
    }
private:

    char* begin() {
        return buffer_;
    }

    const char* begin() const {
        return buffer_;
    }

    void grow(size_t len) {
        if (WritableBytes() + PrependableBytes() < len + reserved_prepend_size_) {
            //grow the capacity
            size_t n = (capacity_ << 1) + len;
            size_t m = length();
            char* d = new char[n];
            memcpy(d + reserved_prepend_size_, begin() + read_index_, m);
            write_index_ = m + reserved_prepend_size_;
            read_index_ = reserved_prepend_size_;
            capacity_ = n;
            delete[] buffer_;
            buffer_ = d;
        } else {
            // move readable data to the front, make space inside buffer
            assert(reserved_prepend_size_ < read_index_);
            size_t readable = length();
            memmove(begin() + reserved_prepend_size_, begin() + read_index_, length());
            read_index_ = reserved_prepend_size_;
            write_index_ = read_index_ + readable;
            assert(readable == length());
            assert(WritableBytes() >= len);
        }
    }

private:
    char* buffer_;
    size_t capacity_;
    size_t read_index_;
    size_t write_index_;
    size_t reserved_prepend_size_;
    static const char kCRLF[];
};

}

以上展示部分buffer的源码,部分常用的方法这里就不展示了

总结:
evpp的时间类和缓存类大程度上借鉴了go的切片的思想

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: libevent是一个开的C语言网络编程库,主要用于处理高并发网络连接。它提供了对事件驱动的支持,使得开发者可以方便地编写高效的并发网络应用程序。 libevent的核心是事件循环机制。在传统的网络编程中,通常需要使用多线程或多进程来处理并发连接,而使用libevent可以通过一个事件循环来处理多个连接。在事件循环中,可以注册多个事件,并定义回调函数来处理事件的触发。当有事件发生时,libevent会调用相应的回调函数来处理事件的处理逻辑。这样可以大大简化并发编程的复杂性,并提高程序的性能。 libevent的事件模型基于操作系统提供的I/O多路复用机制,如select、poll和epoll等。它可以在不同的操作系统平台上运行,并提供一致的接口和高效的事件处理机制。借助这些机制,libevent可以同时处理大量的并发连接,并保持低延迟和高吞吐量。 除了处理网络连接,libevent还提供了其他常用的功能,如定时器和信号处理等。它允许开发者在事件循环中注册定时器事件,可以用于定时任务的调度。同时,libevent还可以处理来自操作系统的信号,并提供了对信号的处理接口,以便开发者能够处理各种系统事件。 总之,libevent是一个功能强大、简单易用的高并发网络编程库,适用于开发各种类型的网络应用。无论是开发服务器、代理、聊天程序还是实时应用,libevent都能帮助开发者快速编写高性能的并发网络程序。 ### 回答2: libevent是一个开的C/C++网络库,用于高性能的事件驱动编程。它提供了一个轻量级、可移植的框架,用于开发高并发的网络应用程序。 它的设计目标是提供一个高效的事件处理器,可以处理成千上万个并发连接,并且支持多线程并发处理。libevent基于事件驱动模型,通过异步I/O和回调函数来实现高并发处理网络请求。 libevent提供了一系列的函数来注册和监听各种网络事件,包括读、写、超时和信号等等。当一个事件发生时,libevent会调用相应的回调函数来处理事件。通过这种方式,我们可以非常方便地处理并发连接,并实现高性能网络编程。 libevent的优点主要包括: 1. 高性能libevent使用异步I/O和事件驱动模型,能够处理成千上万个并发连接,具有很高的处理能力。 2. 可移植性:libevent提供了统一的接口,可以在多种操作系统上运行,包括Linux、Windows、Mac等。 3. 易用性:libevent简单易用,只需注册感兴趣的事件和相应的回调函数,就可以实现高效的网络编程。 4. 多线程支持:libevent支持多线程并发处理,可以充分利用多核CPU的性能优势。 总之,libevent是一款非常适合高并发网络编程的开库,它可以帮助我们实现高性能服务器程序,提升系统的并发处理能力。无论是开发网络服务器还是网络应用程序,libevent都是一个不错的选择。 ### 回答3: libevent 是一个用于高并发网络编程的 C/C++ 库。它提供了一个跨平台的异步事件驱动的网络编程框架,能够实现高效地处理大量并发连接的需求。 libevent 的主要特点包括: 1. 异步事件驱动:libevent 使用事件驱动模型,主要利用非阻塞 I/O 和事件回调机制,能够高效地处理大量并发事件。 2. 跨平台支持:libevent 提供了跨不同操作系统的支持,包括 Windows、Linux、Unix 等,并且提供了统一的 API 接口,方便开发者进行跨平台开发。 3. 支持多种网络协议:libevent 支持 TCP、UDP、HTTP 等多种网络协议,为开发者提供了丰富的网络编程能力。 4. 高性能libevent 的设计目标之一是高性能,它通过使用多路复用技术,将系统资高效地利用起来,能够同时处理大量并发连接,并且保持低延迟。 5. 灵活易用:libevent 提供了简洁的 API,使用起来非常方便,可以快速实现高并发网络编程的需求。 总之,libevent 是一个强大而灵活的 C/C++ 库,适用于各种需要处理高并发连接的网络应用程序。无论是开发高性能服务器、代理、负载均衡器还是其他类似应用,libevent 都是一个值得推荐的选择。它的高效性能、跨平台支持和简洁易用的 API 接口使得开发者能够快速构建稳定可靠的高并发网络应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值