浏览代码

Use old version of ZLToolkit

Qiuyang 1 年之前
父节点
当前提交
d0d5dd9b15
共有 47 个文件被更改,包括 1602 次插入1934 次删除
  1. 154 92
      3rdparty/ZLToolKit/include/Network/Buffer.h
  2. 15 15
      3rdparty/ZLToolKit/include/Network/Server.h
  3. 56 34
      3rdparty/ZLToolKit/include/Network/Session.h
  4. 141 240
      3rdparty/ZLToolKit/include/Network/Socket.h
  5. 40 47
      3rdparty/ZLToolKit/include/Network/TcpClient.h
  6. 22 25
      3rdparty/ZLToolKit/include/Network/TcpServer.h
  7. 65 0
      3rdparty/ZLToolKit/include/Network/TcpSession.h
  8. 14 25
      3rdparty/ZLToolKit/include/Network/UdpServer.h
  9. 89 96
      3rdparty/ZLToolKit/include/Network/sockutil.h
  10. 44 56
      3rdparty/ZLToolKit/include/Poller/EventPoller.h
  11. 10 9
      3rdparty/ZLToolKit/include/Poller/Pipe.h
  12. 11 8
      3rdparty/ZLToolKit/include/Poller/PipeWrap.h
  13. 2 3
      3rdparty/ZLToolKit/include/Poller/SelectWrap.h
  14. 10 5
      3rdparty/ZLToolKit/include/Poller/Timer.h
  15. 18 26
      3rdparty/ZLToolKit/include/Thread/TaskExecutor.h
  16. 18 14
      3rdparty/ZLToolKit/include/Thread/TaskQueue.h
  17. 25 31
      3rdparty/ZLToolKit/include/Thread/ThreadPool.h
  18. 12 13
      3rdparty/ZLToolKit/include/Thread/WorkThreadPool.h
  19. 11 13
      3rdparty/ZLToolKit/include/Thread/semaphore.h
  20. 18 19
      3rdparty/ZLToolKit/include/Thread/threadgroup.h
  21. 193 186
      3rdparty/ZLToolKit/include/Util/CMD.h
  22. 16 44
      3rdparty/ZLToolKit/include/Util/File.h
  23. 5 4
      3rdparty/ZLToolKit/include/Util/List.h
  24. 2 1
      3rdparty/ZLToolKit/include/Util/MD5.h
  25. 26 27
      3rdparty/ZLToolKit/include/Util/NoticeCenter.h
  26. 70 83
      3rdparty/ZLToolKit/include/Util/ResourcePool.h
  27. 146 201
      3rdparty/ZLToolKit/include/Util/RingBuffer.h
  28. 0 3
      3rdparty/ZLToolKit/include/Util/SHA1.h
  29. 27 32
      3rdparty/ZLToolKit/include/Util/SSLBox.h
  30. 17 12
      3rdparty/ZLToolKit/include/Util/SSLUtil.h
  31. 66 73
      3rdparty/ZLToolKit/include/Util/SqlConnection.h
  32. 55 63
      3rdparty/ZLToolKit/include/Util/SqlPool.h
  33. 18 17
      3rdparty/ZLToolKit/include/Util/TimeTicker.h
  34. 4 3
      3rdparty/ZLToolKit/include/Util/base64.h
  35. 1 1
      3rdparty/ZLToolKit/include/Util/function_traits.h
  36. 64 157
      3rdparty/ZLToolKit/include/Util/logger.h
  37. 49 78
      3rdparty/ZLToolKit/include/Util/mini.h
  38. 12 11
      3rdparty/ZLToolKit/include/Util/onceToken.h
  39. 44 155
      3rdparty/ZLToolKit/include/Util/util.h
  40. 7 7
      3rdparty/ZLToolKit/include/Util/uv_errno.h
  41. 二进制
      3rdparty/ZLToolKit/lib/libZLToolKit.a
  42. 二进制
      3rdparty/ZLToolKit/lib/libZLToolKit.so
  43. 二进制
      lib/libgsd_modules.so
  44. 二进制
      lib/libgsd_plugins.so
  45. 2 2
      modules/Expel/src/Expel.cpp
  46. 1 1
      modules/TCPClient/include/TCPClient.hpp
  47. 2 2
      modules/TCPClient/src/TCPClient.cpp

+ 154 - 92
3rdparty/ZLToolKit/include/Network/Buffer.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,40 +11,46 @@
 #ifndef ZLTOOLKIT_BUFFER_H
 #define ZLTOOLKIT_BUFFER_H
 
-#include <cassert>
+#include <assert.h>
 #include <memory>
 #include <string>
+#include <deque>
+#include <mutex>
 #include <vector>
+#include <atomic>
+#include <sstream>
 #include <type_traits>
 #include <functional>
 #include "Util/util.h"
+#include "Util/List.h"
+#include "Util/uv_errno.h"
 #include "Util/ResourcePool.h"
+#include "Network/sockutil.h"
+using namespace std;
 
 namespace toolkit {
 
 template <typename T> struct is_pointer : public std::false_type {};
-template <typename T> struct is_pointer<std::shared_ptr<T> > : public std::true_type {};
-template <typename T> struct is_pointer<std::shared_ptr<T const> > : public std::true_type {};
-template <typename T> struct is_pointer<T*> : public std::true_type {};
-template <typename T> struct is_pointer<const T*> : public std::true_type {};
+template <typename T> struct is_pointer<shared_ptr<T> > : public std::true_type {};
+template <typename T> struct is_pointer<shared_ptr<T const> > : public std::true_type {};
+template <typename T> struct is_pointer<T*> : public true_type {};
+template <typename T> struct is_pointer<const T*> : public true_type {};
 
 //缓存基类
 class Buffer : public noncopyable {
 public:
-    using Ptr = std::shared_ptr<Buffer>;
-
-    Buffer() = default;
-    virtual ~Buffer() = default;
-
+    typedef std::shared_ptr<Buffer> Ptr;
+    Buffer(){};
+    virtual ~Buffer(){};
     //返回数据长度
-    virtual char *data() const = 0;
+    virtual char *data() const = 0 ;
     virtual size_t size() const = 0;
 
-    virtual std::string toString() const {
-        return std::string(data(), size());
+    virtual string toString() const {
+        return string(data(),size());
     }
 
-    virtual size_t getCapacity() const {
+    virtual size_t getCapacity() const{
         return size();
     }
 
@@ -56,24 +62,24 @@ private:
 template <typename C>
 class BufferOffset : public  Buffer {
 public:
-    using Ptr = std::shared_ptr<BufferOffset>;
+    typedef std::shared_ptr<BufferOffset> Ptr;
 
     BufferOffset(C data, size_t offset = 0, size_t len = 0) : _data(std::move(data)) {
         setup(offset, len);
     }
 
-    ~BufferOffset() override = default;
+    ~BufferOffset() {}
 
     char *data() const override {
         return const_cast<char *>(getPointer<C>(_data)->data()) + _offset;
     }
 
-    size_t size() const override {
+    size_t size() const override{
         return _size;
     }
 
-    std::string toString() const override {
-        return std::string(data(), size());
+    string toString() const override {
+        return string(data(),size());
     }
 
 private:
@@ -88,94 +94,89 @@ private:
     }
 
     template<typename T>
-    static typename std::enable_if<::toolkit::is_pointer<T>::value, const T &>::type
+    static typename std::enable_if<toolkit::is_pointer<T>::value, const T &>::type
     getPointer(const T &data) {
         return data;
     }
 
     template<typename T>
-    static typename std::enable_if<!::toolkit::is_pointer<T>::value, const T *>::type
+    static typename std::enable_if<!toolkit::is_pointer<T>::value, const T *>::type
     getPointer(const T &data) {
         return &data;
     }
 
 private:
     C _data;
-    size_t _size;
     size_t _offset;
+    size_t _size;
 };
 
-using BufferString = BufferOffset<std::string>;
+typedef BufferOffset<string> BufferString;
 
 //指针式缓存对象,
-class BufferRaw : public Buffer {
+class BufferRaw : public Buffer{
 public:
     using Ptr = std::shared_ptr<BufferRaw>;
 
     static Ptr create();
 
-    ~BufferRaw() override {
-        if (_data) {
-            delete[] _data;
+    ~BufferRaw() override{
+        if(_data){
+            delete [] _data;
         }
     }
-
     //在写入数据时请确保内存是否越界
     char *data() const override {
         return _data;
     }
-
     //有效数据大小
-    size_t size() const override {
+    size_t size() const override{
         return _size;
     }
-
     //分配内存大小
-    void setCapacity(size_t capacity) {
-        if (_data) {
-            do {
-                if (capacity > _capacity) {
+    void setCapacity(size_t capacity){
+        if(_data){
+            do{
+                if(capacity > _capacity){
                     //请求的内存大于当前内存,那么重新分配
                     break;
                 }
 
-                if (_capacity < 2 * 1024) {
+                if(_capacity < 2 * 1024){
                     //2K以下,不重复开辟内存,直接复用
                     return;
                 }
 
-                if (2 * capacity > _capacity) {
+                if(2 * capacity > _capacity){
                     //如果请求的内存大于当前内存的一半,那么也复用
                     return;
                 }
-            } while (false);
+            }while(false);
 
-            delete[] _data;
+            delete [] _data;
         }
         _data = new char[capacity];
         _capacity = capacity;
     }
-
     //设置有效数据大小
-    virtual void setSize(size_t size) {
-        if (size > _capacity) {
+    void setSize(size_t size){
+        if(size > _capacity){
             throw std::invalid_argument("Buffer::setSize out of range");
         }
         _size = size;
     }
-
     //赋值数据
-    void assign(const char *data, size_t size = 0) {
-        if (size <= 0) {
+    void assign(const char *data,size_t size = 0){
+        if(size <=0 ){
             size = strlen(data);
         }
         setCapacity(size + 1);
-        memcpy(_data, data, size);
+        memcpy(_data,data,size);
         _data[size] = '\0';
         setSize(size);
     }
 
-    size_t getCapacity() const override {
+    size_t getCapacity() const override{
         return _capacity;
     }
 
@@ -183,15 +184,16 @@ protected:
     friend class ResourcePool_l<BufferRaw>;
 
     BufferRaw(size_t capacity = 0) {
-        if (capacity) {
+        if(capacity){
             setCapacity(capacity);
         }
     }
 
-    BufferRaw(const char *data, size_t size = 0) {
-        assign(data, size);
+    BufferRaw(const char *data,size_t size = 0){
+        assign(data,size);
     }
 
+
 private:
     size_t _size = 0;
     size_t _capacity = 0;
@@ -202,36 +204,36 @@ private:
 
 class BufferLikeString : public Buffer {
 public:
-    ~BufferLikeString() override = default;
+    ~BufferLikeString() override {}
 
     BufferLikeString() {
         _erase_head = 0;
-        _erase_tail = 0;
+        _erase_tail  = 0;
     }
 
-    BufferLikeString(std::string str) {
+    BufferLikeString(string str) {
         _str = std::move(str);
         _erase_head = 0;
-        _erase_tail = 0;
+        _erase_tail  = 0;
     }
 
-    BufferLikeString &operator=(std::string str) {
+    BufferLikeString& operator= (string str){
         _str = std::move(str);
         _erase_head = 0;
-        _erase_tail = 0;
+        _erase_tail  = 0;
         return *this;
     }
 
     BufferLikeString(const char *str) {
         _str = str;
         _erase_head = 0;
-        _erase_tail = 0;
+        _erase_tail  = 0;
     }
 
-    BufferLikeString &operator=(const char *str) {
+    BufferLikeString& operator= (const char *str){
         _str = str;
         _erase_head = 0;
-        _erase_tail = 0;
+        _erase_tail  = 0;
         return *this;
     }
 
@@ -243,7 +245,7 @@ public:
         that._erase_tail = 0;
     }
 
-    BufferLikeString &operator=(BufferLikeString &&that) {
+    BufferLikeString& operator= (BufferLikeString &&that){
         _str = std::move(that._str);
         _erase_head = that._erase_head;
         _erase_tail = that._erase_tail;
@@ -258,25 +260,25 @@ public:
         _erase_tail = that._erase_tail;
     }
 
-    BufferLikeString &operator=(const BufferLikeString &that) {
+    BufferLikeString& operator= (const BufferLikeString &that){
         _str = that._str;
         _erase_head = that._erase_head;
         _erase_tail = that._erase_tail;
         return *this;
     }
 
-    char *data() const override {
-        return (char *) _str.data() + _erase_head;
+    char* data() const override{
+        return (char *)_str.data() + _erase_head;
     }
 
-    size_t size() const override {
+    size_t size() const override{
         return _str.size() - _erase_tail - _erase_head;
     }
 
-    BufferLikeString &erase(size_t pos = 0, size_t n = std::string::npos) {
+    BufferLikeString& erase(size_t pos = 0, size_t n = string::npos) {
         if (pos == 0) {
             //移除前面的数据
-            if (n != std::string::npos) {
+            if (n != string::npos) {
                 //移除部分
                 if (n > size()) {
                     //移除太多数据了
@@ -294,7 +296,7 @@ public:
             return *this;
         }
 
-        if (n == std::string::npos || pos + n >= size()) {
+        if (n == string::npos || pos + n >= size()) {
             //移除末尾所有数据
             if (pos >= size()) {
                 //移除太多数据
@@ -314,19 +316,19 @@ public:
         return *this;
     }
 
-    BufferLikeString &append(const BufferLikeString &str) {
+    BufferLikeString& append(const BufferLikeString &str){
         return append(str.data(), str.size());
     }
 
-    BufferLikeString &append(const std::string &str) {
+    BufferLikeString& append(const string &str){
         return append(str.data(), str.size());
     }
 
-    BufferLikeString &append(const char *data) {
+    BufferLikeString& append(const char *data){
         return append(data, strlen(data));
     }
 
-    BufferLikeString &append(const char *data, size_t len) {
+    BufferLikeString& append(const char *data, size_t len){
         if (len <= 0) {
             return *this;
         }
@@ -341,8 +343,8 @@ public:
         return *this;
     }
 
-    void push_back(char c) {
-        if (_erase_tail == 0) {
+    void push_back(char c){
+        if(_erase_tail == 0){
             _str.push_back(c);
             return;
         }
@@ -351,16 +353,16 @@ public:
         data()[size()] = '\0';
     }
 
-    BufferLikeString &insert(size_t pos, const char *s, size_t n) {
+    BufferLikeString& insert(size_t pos, const char* s, size_t n){
         _str.insert(_erase_head + pos, s, n);
         return *this;
     }
 
-    BufferLikeString &assign(const char *data) {
+    BufferLikeString& assign(const char *data) {
         return assign(data, strlen(data));
     }
 
-    BufferLikeString &assign(const char *data, size_t len) {
+    BufferLikeString& assign(const char *data, size_t len) {
         if (len <= 0) {
             return *this;
         }
@@ -384,37 +386,31 @@ public:
         _str.clear();
     }
 
-    char &operator[](size_t pos) {
+    char& operator[](size_t pos){
         if (pos >= size()) {
             throw std::out_of_range("BufferLikeString::operator[] out_of_range");
         }
         return data()[pos];
     }
 
-    const char &operator[](size_t pos) const {
+    const char& operator[](size_t pos) const{
         return (*const_cast<BufferLikeString *>(this))[pos];
     }
 
-    size_t capacity() const {
+    size_t capacity() const{
         return _str.capacity();
     }
 
-    void reserve(size_t size) {
+    void reserve(size_t size){
         _str.reserve(size);
     }
 
-    void resize(size_t size, char c = '\0') {
-        _str.resize(size, c);
-        _erase_head = 0;
-        _erase_tail = 0;
-    }
-
-    bool empty() const {
+    bool empty() const{
         return size() <= 0;
     }
 
-    std::string substr(size_t pos, size_t n = std::string::npos) const {
-        if (n == std::string::npos) {
+    string substr(size_t pos, size_t n = string::npos) const{
+        if (n == string::npos) {
             //获取末尾所有的
             if (pos >= size()) {
                 throw std::out_of_range("BufferLikeString::substr out_of_range");
@@ -430,7 +426,7 @@ public:
     }
 
 private:
-    void moveData() {
+    void moveData(){
         if (_erase_head) {
             _str.erase(0, _erase_head);
             _erase_head = 0;
@@ -440,10 +436,76 @@ private:
 private:
     size_t _erase_head;
     size_t _erase_tail;
-    std::string _str;
+    string _str;
     //对象个数统计
     ObjectStatistic<BufferLikeString> _statistic;
 };
 
+#if defined(_WIN32)
+struct iovec {
+    void *   iov_base;	/* [XSI] Base address of I/O memory region */
+    size_t	 iov_len;	/* [XSI] Size of region iov_base points to */
+};
+struct msghdr {
+    void		*msg_name;	/* [XSI] optional address */
+    size_t  	msg_namelen;	/* [XSI] size of address */
+    struct		iovec *msg_iov;	/* [XSI] scatter/gather array */
+    size_t 		msg_iovlen;	/* [XSI] # elements in msg_iov */
+    void		*msg_control;	/* [XSI] ancillary data, see below */
+    int			msg_controllen;	/* [XSI] ancillary data buffer len */
+    int			msg_flags;	/* [XSI] flags on received message */
+};
+#else
+#include <sys/uio.h>
+#include <limits.h>
+#endif
+
+#if !defined(IOV_MAX)
+#define IOV_MAX 1024
+#endif
+
+class BufferList;
+class BufferSock : public Buffer {
+public:
+    using Ptr = std::shared_ptr<BufferSock>;
+    friend class BufferList;
+
+    BufferSock(Buffer::Ptr ptr, struct sockaddr *addr = nullptr, int addr_len = 0);
+    ~BufferSock();
+
+    char *data() const override;
+    size_t size() const override;
+
+private:
+    int _addr_len = 0;
+    struct sockaddr *_addr = nullptr;
+    Buffer::Ptr _buffer;
+};
+
+class BufferList : public noncopyable {
+public:
+    using Ptr = std::shared_ptr<BufferList>;
+    using SendResult = function<void(const Buffer::Ptr &buffer, bool send_success)>;
+    BufferList(List<std::pair<Buffer::Ptr, bool> > &list, SendResult cb = nullptr);
+    ~BufferList();
+
+    bool empty();
+    size_t count();
+    ssize_t send(int fd, int flags, bool udp);
+
+private:
+    void reOffset(size_t n);
+    ssize_t send_l(int fd, int flags, bool udp);
+
+private:
+    size_t _iovec_off = 0;
+    size_t _remain_size = 0;
+    vector<struct iovec> _iovec;
+    List<std::pair<Buffer::Ptr, bool> > _pkt_list;
+    SendResult _cb;
+    //对象个数统计
+    ObjectStatistic<BufferList> _statistic;
+};
+
 }//namespace toolkit
 #endif //ZLTOOLKIT_BUFFER_H

+ 15 - 15
3rdparty/ZLToolKit/include/Network/Server.h

@@ -12,8 +12,9 @@
 #define ZLTOOLKIT_SERVER_H
 
 #include <unordered_map>
+
+#include "Network/Session.h"
 #include "Util/mini.h"
-#include "Session.h"
 
 namespace toolkit {
 
@@ -26,50 +27,49 @@ public:
 
     //单例
     static SessionMap &Instance();
-    ~SessionMap() = default;
+    ~SessionMap() {};
 
     //获取Session
-    Session::Ptr get(const std::string &tag);
-    void for_each_session(const std::function<void(const std::string &id, const Session::Ptr &session)> &cb);
+    Session::Ptr get(const string &tag);
+    void for_each_session(const function<void(const string &id, const Session::Ptr &session)> &cb);
 
 private:
     SessionMap() = default;
 
     //移除Session
-    bool del(const std::string &tag);
+    bool del(const string &tag);
     //添加Session
-    bool add(const std::string &tag, const Session::Ptr &session);
+    bool add(const string &tag, const Session::Ptr &session);
 
 private:
-    std::mutex _mtx_session;
-    std::unordered_map<std::string, std::weak_ptr<Session> > _map_session;
+    mutex _mtx_session;
+    unordered_map<string, weak_ptr<Session> > _map_session;
 };
 
 class Server;
-
 class SessionHelper {
 public:
     using Ptr = std::shared_ptr<SessionHelper>;
 
-    SessionHelper(const std::weak_ptr<Server> &server, Session::Ptr session, std::string cls);
+    SessionHelper(const std::weak_ptr<Server> &server, Session::Ptr session);
     ~SessionHelper();
 
     const Session::Ptr &session() const;
-    const std::string &className() const;
 
 private:
-    std::string _cls;
-    std::string _identifier;
+    string _identifier;
     Session::Ptr _session;
     SessionMap::Ptr _session_map;
     std::weak_ptr<Server> _server;
 };
 
+//
 // server 基类, 暂时仅用于剥离 SessionHelper 对 TcpServer 的依赖
 // 后续将 TCP 与 UDP 服务通用部分加到这里.
+//
 class Server : public std::enable_shared_from_this<Server>, public mINI {
 public:
-    using Ptr = std::shared_ptr<Server>;
+    using Ptr =  std::shared_ptr<Server>;
 
     explicit Server(EventPoller::Ptr poller = nullptr);
     virtual ~Server() = default;
@@ -80,4 +80,4 @@ protected:
 
 } // namespace toolkit
 
-#endif // ZLTOOLKIT_SERVER_H
+#endif // ZLTOOLKIT_SERVER_H

+ 56 - 34
3rdparty/ZLToolKit/include/Network/Session.h

@@ -12,29 +12,44 @@
 #define ZLTOOLKIT_SESSION_H
 
 #include <memory>
-#include "Socket.h"
+
+#include "Network/Socket.h"
 #include "Util/util.h"
-#include "Util/SSLBox.h"
 
 namespace toolkit {
 
 // 会话, 用于存储一对客户端与服务端间的关系
 class Server;
-class TcpSession;
-class UdpSession;
-
-class Session : public SocketHelper {
+class Session : public std::enable_shared_from_this<Session>, public SocketHelper {
 public:
-    using Ptr = std::shared_ptr<Session>;
+    typedef std::shared_ptr<Session> Ptr;
 
     Session(const Socket::Ptr &sock);
-    ~Session() override = default;
+    ~Session() override;
+
+    /**
+     * 接收数据入口
+     * @param buf 数据,可以重复使用内存区
+     */
+    virtual void onRecv(const Buffer::Ptr &buf) = 0;
+
+    /**
+     * 收到 eof 或其他导致脱离 Server 事件的回调
+     * 收到该事件时, 该对象一般将立即被销毁
+     * @param err 原因
+     */
+    virtual void onErr(const SockException &ex) = 0;
+
+    /**
+     * 每隔一段时间触发, 用来做超时管理
+     */
+    virtual void onManager() = 0;
 
     /**
      * 在创建 Session 后, Server 会把自身的配置参数通过该函数传递给 Session
      * @param server, 服务器对象
      */
-    virtual void attachServer(const Server &server) {}
+    virtual void attachServer(const Server &) {}
 
     /**
      * 作为该 Session 的唯一标识符
@@ -42,44 +57,51 @@ public:
      */
     std::string getIdentifier() const override;
 
+    /**
+     * 线程安全的脱离 Server 并触发 onError 事件
+     * @param ex 触发 onError 事件的原因
+     */
+    void safeShutdown(const SockException &ex = SockException(Err_shutdown, "self shutdown"));
+
 private:
-    mutable std::string _id;
-    std::unique_ptr<toolkit::ObjectStatistic<toolkit::TcpSession> > _statistic_tcp;
-    std::unique_ptr<toolkit::ObjectStatistic<toolkit::UdpSession> > _statistic_udp;
+    // 对象个数统计
+    ObjectStatistic<Session> _statistic;
 };
 
-// 通过该模板可以让TCP服务器快速支持TLS
-template <typename SessionType>
-class SessionWithSSL : public SessionType {
+//TCP服务器连接对象,一个tcp连接对应一个TcpSession对象
+class TcpSession : public Session {
 public:
-    template <typename... ArgsType>
-    SessionWithSSL(ArgsType &&...args)
-        : SessionType(std::forward<ArgsType>(args)...) {
-        _ssl_box.setOnEncData([&](const Buffer::Ptr &buf) { public_send(buf); });
-        _ssl_box.setOnDecData([&](const Buffer::Ptr &buf) { public_onRecv(buf); });
-    }
+    using Ptr = std::shared_ptr<TcpSession>;
 
-    ~SessionWithSSL() override { _ssl_box.flush(); }
+    TcpSession(const Socket::Ptr &sock) : Session(sock) {}
+    ~TcpSession() override = default;
 
-    void onRecv(const Buffer::Ptr &buf) override { _ssl_box.onRecv(buf); }
+    Ptr shared_from_this() {
+        return static_pointer_cast<TcpSession>(Session::shared_from_this());
+    }
 
-    // 添加public_onRecv和public_send函数是解决较低版本gcc一个lambad中不能访问protected或private方法的bug
-    inline void public_onRecv(const Buffer::Ptr &buf) { SessionType::onRecv(buf); }
-    inline void public_send(const Buffer::Ptr &buf) { SessionType::send(std::move(const_cast<Buffer::Ptr &>(buf))); }
+private:
+    // 对象个数统计
+    ObjectStatistic<TcpSession> _statistic;
+};
+
+//UDP服务器连接对象,一个udp peer对应一个UdpSession对象
+class UdpSession : public Session {
+public:
+    using Ptr = std::shared_ptr<UdpSession>;
 
-    bool overSsl() const override { return true; }
+    UdpSession(const Socket::Ptr &sock) : Session(sock){}
+    ~UdpSession() override = default;
 
-protected:
-    ssize_t send(Buffer::Ptr buf) override {
-        auto size = buf->size();
-        _ssl_box.onSend(std::move(buf));
-        return size;
+    Ptr shared_from_this() {
+        return static_pointer_cast<UdpSession>(Session::shared_from_this());
     }
 
 private:
-    SSL_Box _ssl_box;
+    // 对象个数统计
+    ObjectStatistic<UdpSession> _statistic;
 };
 
 } // namespace toolkit
 
-#endif // ZLTOOLKIT_SESSION_H
+#endif // ZLTOOLKIT_SESSION_H

+ 141 - 240
3rdparty/ZLToolKit/include/Network/Socket.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -13,15 +13,22 @@
 
 #include <memory>
 #include <string>
+#include <deque>
 #include <mutex>
+#include <vector>
 #include <atomic>
 #include <sstream>
 #include <functional>
-#include "Util/SpeedStatistic.h"
-#include "sockutil.h"
+#include "Util/util.h"
+#include "Util/onceToken.h"
+#include "Util/uv_errno.h"
+#include "Util/TimeTicker.h"
+#include "Util/ResourcePool.h"
 #include "Poller/Timer.h"
 #include "Poller/EventPoller.h"
-#include "BufferSock.h"
+#include "Network/sockutil.h"
+#include "Buffer.h"
+using namespace std;
 
 namespace toolkit {
 
@@ -61,100 +68,89 @@ typedef enum {
 } ErrCode;
 
 //错误信息类
-class SockException : public std::exception {
+class SockException: public std::exception {
 public:
-    SockException(ErrCode code = Err_success, const std::string &msg = "", int custom_code = 0) {
-        _msg = msg;
-        _code = code;
-        _custom_code = custom_code;
+    SockException(ErrCode errCode = Err_success,
+                  const string &errMsg = "",
+                  int customCode = 0) {
+        _errMsg = errMsg;
+        _errCode = errCode;
+        _customCode = customCode;
     }
 
     //重置错误
-    void reset(ErrCode code, const std::string &msg, int custom_code = 0) {
-        _msg = msg;
-        _code = code;
-        _custom_code = custom_code;
+    void reset(ErrCode errCode, const string &errMsg) {
+        _errMsg = errMsg;
+        _errCode = errCode;
     }
-
     //错误提示
-    const char *what() const noexcept override {
-        return _msg.c_str();
+    const char* what() const noexcept override{
+        return _errMsg.c_str();
     }
-
     //错误代码
     ErrCode getErrCode() const {
-        return _code;
-    }
-
-    //用户自定义错误代码
-    int getCustomCode() const {
-        return _custom_code;
+        return _errCode;
     }
-
     //判断是否真的有错
-    operator bool() const {
-        return _code != Err_success;
+    operator bool() const{
+        return _errCode != Err_success;
     }
-
+    //用户自定义错误代码
+    int getCustomCode () const{
+        return _customCode;
+    }
+    //获取用户自定义错误代码
+    void setCustomCode(int code) {
+        _customCode = code;
+    };
 private:
-    ErrCode _code;
-    int _custom_code = 0;
-    std::string _msg;
+    string _errMsg;
+    ErrCode _errCode;
+    int _customCode = 0;
 };
 
-//std::cout等输出流可以直接输出SockException对象
-std::ostream &operator<<(std::ostream &ost, const SockException &err);
-
-class SockNum {
+class SockNum{
 public:
-    using Ptr = std::shared_ptr<SockNum>;
-
     typedef enum {
-        Sock_Invalid = -1,
         Sock_TCP = 0,
-        Sock_UDP = 1,
-        Sock_TCP_Server = 2
+        Sock_UDP = 1
     } SockType;
 
-    SockNum(int fd, SockType type) {
+    typedef std::shared_ptr<SockNum> Ptr;
+    SockNum(int fd,SockType type){
         _fd = fd;
         _type = type;
     }
-
-    ~SockNum() {
+    ~SockNum(){
 #if defined (OS_IPHONE)
         unsetSocketOfIOS(_fd);
 #endif //OS_IPHONE
-        // 停止socket收发能力
         ::shutdown(_fd, SHUT_RDWR);
         close(_fd);
     }
 
-    int rawFd() const {
+    int rawFd() const{
         return _fd;
     }
 
-    SockType type() {
+    SockType type(){
         return _type;
     }
 
-    void setConnected() {
+    void setConnected(){
 #if defined (OS_IPHONE)
         setSocketOfIOS(_fd);
 #endif //OS_IPHONE
     }
-
-#if defined (OS_IPHONE)
 private:
-    void *readStream=nullptr;
-    void *writeStream=nullptr;
+    SockType _type;
+    int _fd;
+#if defined (OS_IPHONE)
+    void *readStream=NULL;
+    void *writeStream=NULL;
     bool setSocketOfIOS(int socket);
     void unsetSocketOfIOS(int socket);
 #endif //OS_IPHONE
-
-private:
-    int _fd;
-    SockType _type;
 };
 
 //socket 文件描述符的包装
@@ -162,15 +158,14 @@ private:
 //防止描述符溢出
 class SockFD : public noncopyable {
 public:
-    using Ptr = std::shared_ptr<SockFD>;
-
+    typedef std::shared_ptr<SockFD> Ptr;
     /**
      * 创建一个fd对象
      * @param num 文件描述符,int数字
      * @param poller 事件监听器
      */
-    SockFD(int num, SockNum::SockType type, const EventPoller::Ptr &poller) {
-        _num = std::make_shared<SockNum>(num, type);
+    SockFD(int num,SockNum::SockType type,const EventPoller::Ptr &poller){
+        _num = std::make_shared<SockNum>(num,type);
         _poller = poller;
     }
 
@@ -179,23 +174,17 @@ public:
      * @param that 源对象
      * @param poller 事件监听器
      */
-    SockFD(const SockFD &that, const EventPoller::Ptr &poller) {
+    SockFD(const SockFD &that,const EventPoller::Ptr &poller){
         _num = that._num;
         _poller = poller;
-        if (_poller == that._poller) {
-            throw std::invalid_argument("Copy a SockFD with same poller");
+        if(_poller == that._poller){
+            throw invalid_argument("copy a SockFD with same poller!");
         }
     }
 
-     ~SockFD() { delEvent(); }
-
-    void delEvent() {
-        if (_poller) {
-            auto num = _num;
-            // 移除io事件成功后再close fd
-            _poller->delEvent(num->rawFd(), [num](bool) {});
-            _poller = nullptr;
-        }
+    ~SockFD() {
+        auto num = _num;
+        _poller->delEvent(_num->rawFd(), [num](bool) {});
     }
 
     void setConnected() {
@@ -215,27 +204,24 @@ private:
     EventPoller::Ptr _poller;
 };
 
-template<class Mtx = std::recursive_mutex>
+template <class Mtx = recursive_mutex>
 class MutexWrapper {
 public:
-    MutexWrapper(bool enable) {
+    MutexWrapper(bool enable){
         _enable = enable;
     }
+    ~MutexWrapper(){}
 
-    ~MutexWrapper() = default;
-
-    inline void lock() {
-        if (_enable) {
+    inline void lock(){
+        if(_enable){
             _mtx.lock();
         }
     }
-
-    inline void unlock() {
-        if (_enable) {
+    inline void unlock(){
+        if(_enable){
             _mtx.unlock();
         }
     }
-
 private:
     bool _enable;
     Mtx _mtx;
@@ -247,15 +233,15 @@ public:
     virtual ~SockInfo() = default;
 
     //获取本机ip
-    virtual std::string get_local_ip() = 0;
+    virtual string get_local_ip() = 0;
     //获取本机端口号
     virtual uint16_t get_local_port() = 0;
     //获取对方ip
-    virtual std::string get_peer_ip() = 0;
+    virtual string  get_peer_ip() = 0;
     //获取对方端口号
     virtual uint16_t get_peer_port() = 0;
     //获取标识符
-    virtual std::string getIdentifier() const { return ""; }
+    virtual string getIdentifier() const { return ""; }
 };
 
 #define TraceP(ptr) TraceL << ptr->getIdentifier() << "(" << ptr->get_peer_ip() << ":" << ptr->get_peer_port() << ") "
@@ -269,15 +255,15 @@ class Socket : public std::enable_shared_from_this<Socket>, public noncopyable,
 public:
     using Ptr = std::shared_ptr<Socket>;
     //接收数据回调
-    using onReadCB = std::function<void(const Buffer::Ptr &buf, struct sockaddr *addr, int addr_len)>;
+    using onReadCB = function<void(const Buffer::Ptr &buf, struct sockaddr *addr, int addr_len)>;
     //发生错误回调
-    using onErrCB = std::function<void(const SockException &err)>;
+    using onErrCB = function<void(const SockException &err)>;
     //tcp监听接收到连接请求
-    using onAcceptCB = std::function<void(Socket::Ptr &sock, std::shared_ptr<void> &complete)>;
+    using onAcceptCB = function<void(Socket::Ptr &sock, shared_ptr<void> &complete)>;
     //socket发送缓存清空事件,返回true代表下次继续监听该事件,否则停止
-    using onFlush = std::function<bool()>;
+    using onFlush = function<bool()>;
     //在接收到连接请求前,拦截Socket默认生成方式
-    using onCreateSocket = std::function<Ptr(const EventPoller::Ptr &poller)>;
+    using onCreateSocket = function<Ptr(const EventPoller::Ptr &poller)>;
     //发送buffer成功与否回调
     using onSendResult = BufferList::SendResult;
 
@@ -288,6 +274,7 @@ public:
     */
     static Ptr createSocket(const EventPoller::Ptr &poller = nullptr, bool enable_mutex = true);
     Socket(const EventPoller::Ptr &poller = nullptr, bool enable_mutex = true);
+
     ~Socket() override;
 
     /**
@@ -299,8 +286,8 @@ public:
      * @param local_ip 绑定本地网卡ip
      * @param local_port 绑定本地网卡端口号
      */
-    void connect(const std::string &url, uint16_t port, const onErrCB &con_cb, float timeout_sec = 5, const std::string &local_ip = "::", uint16_t local_port = 0);
-
+    virtual void connect(const string &url, uint16_t port, onErrCB con_cb, float timeout_sec = 5,
+                 const string &local_ip = "0.0.0.0", uint16_t local_port = 0);
     /**
      * 创建tcp监听服务器
      * @param port 监听端口,0则随机
@@ -308,7 +295,7 @@ public:
      * @param backlog tcp最大积压数
      * @return 是否成功
      */
-    bool listen(uint16_t port, const std::string &local_ip = "::", int backlog = 1024);
+    virtual bool listen(uint16_t port, const string &local_ip = "0.0.0.0", int backlog = 1024);
 
     /**
      * 创建udp套接字,udp是无连接的,所以可以作为服务器和客户端
@@ -316,22 +303,7 @@ public:
      * @param local_ip 绑定的网卡ip
      * @return 是否成功
      */
-    bool bindUdpSock(uint16_t port, const std::string &local_ip = "::", bool enable_reuse = true);
-
-    /**
-     * 包装外部fd,本对象负责close fd
-     * 内部会设置fd为NoBlocked,NoSigpipe,CloExec
-     * 其他设置需要自行使用SockUtil进行设置
-     */
-    bool fromSock(int fd, SockNum::SockType type);
-
-    /**
-     * 从另外一个Socket克隆
-     * 目的是一个socket可以被多个poller对象监听,提高性能或实现Socket归属线程的迁移
-     * @param other 原始的socket对象
-     * @return 是否成功
-     */
-    bool cloneSocket(const Socket &other);
+    virtual bool bindUdpSock(uint16_t port, const string &local_ip = "0.0.0.0");
 
     ////////////设置事件回调////////////
 
@@ -339,38 +311,38 @@ public:
      * 设置数据接收回调,tcp或udp客户端有效
      * @param cb 回调对象
      */
-    void setOnRead(onReadCB cb);
+    virtual void setOnRead(onReadCB cb);
 
     /**
      * 设置异常事件(包括eof等)回调
      * @param cb 回调对象
      */
-    void setOnErr(onErrCB cb);
+    virtual void setOnErr(onErrCB cb);
 
     /**
      * 设置tcp监听接收到连接回调
      * @param cb 回调对象
      */
-    void setOnAccept(onAcceptCB cb);
+    virtual void setOnAccept(onAcceptCB cb);
 
     /**
      * 设置socket写缓存清空事件回调
      * 通过该回调可以实现发送流控
      * @param cb 回调对象
      */
-    void setOnFlush(onFlush cb);
+    virtual void setOnFlush(onFlush cb);
 
     /**
      * 设置accept时,socket构造事件回调
      * @param cb 回调
      */
-    void setOnBeforeAccept(onCreateSocket cb);
+    virtual void setOnBeforeAccept(onCreateSocket cb);
 
     /**
      * 设置发送buffer结果回调
      * @param cb 回调
      */
-    void setOnSendResult(onSendResult cb);
+    virtual void setOnSendResult(onSendResult cb);
 
     ////////////发送数据相关接口////////////
 
@@ -388,67 +360,58 @@ public:
     /**
      * 发送string
      */
-    ssize_t send(std::string buf, struct sockaddr *addr = nullptr, socklen_t addr_len = 0, bool try_flush = true);
+    ssize_t send(string buf, struct sockaddr *addr = nullptr, socklen_t addr_len = 0, bool try_flush = true);
 
     /**
      * 发送Buffer对象,Socket对象发送数据的统一出口
      * socket对象发送数据的统一出口
      */
-    ssize_t send(Buffer::Ptr buf, struct sockaddr *addr = nullptr, socklen_t addr_len = 0, bool try_flush = true);
-
-    /**
-     * 尝试将所有数据写socket
-     * @return -1代表失败(socket无效或者发送超时),0代表成功?
-     */
-    int flushAll();
+    virtual ssize_t send(Buffer::Ptr buf, struct sockaddr *addr = nullptr, socklen_t addr_len = 0, bool try_flush = true);
 
     /**
      * 关闭socket且触发onErr回调,onErr回调将在poller线程中进行
      * @param err 错误原因
      * @return 是否成功触发onErr回调
      */
-    bool emitErr(const SockException &err) noexcept;
+    virtual bool emitErr(const SockException &err) noexcept;
 
     /**
      * 关闭或开启数据接收
      * @param enabled 是否开启
      */
-    void enableRecv(bool enabled);
+    virtual void enableRecv(bool enabled);
 
     /**
      * 获取裸文件描述符,请勿进行close操作(因为Socket对象会管理其生命周期)
      * @return 文件描述符
      */
-    int rawFD() const;
-
-    /**
-     * tcp客户端是否处于连接状态
-     * 支持Sock_TCP类型socket
-     */
-    bool alive() const;
-
-    /**
-     * 返回socket类型
-     */
-    SockNum::SockType sockType() const;
+    virtual int rawFD() const;
 
     /**
      * 设置发送超时主动断开时间;默认10秒
      * @param second 发送超时数据,单位秒
      */
-    void setSendTimeOutSecond(uint32_t second);
+    virtual void setSendTimeOutSecond(uint32_t second);
 
     /**
      * 套接字是否忙,如果套接字写缓存已满则返回true
      * @return 套接字是否忙
      */
-    bool isSocketBusy() const;
+    virtual bool isSocketBusy() const;
 
     /**
      * 获取poller线程对象
      * @return poller线程对象
      */
-    const EventPoller::Ptr &getPoller() const;
+    virtual const EventPoller::Ptr &getPoller() const;
+
+    /**
+     * 从另外一个Socket克隆
+     * 目的是一个socket可以被多个poller对象监听,提高性能
+     * @param other 原始的socket对象
+     * @return 是否成功
+     */
+    virtual bool cloneFromListenSocket(const Socket &other);
 
     /**
      * 绑定udp 目标地址,后续发送时就不用再单独指定了
@@ -456,64 +419,50 @@ public:
      * @param addr_len 目标地址长度
      * @return 是否成功
      */
-    bool bindPeerAddr(const struct sockaddr *dst_addr, socklen_t addr_len = 0);
+    virtual bool bindPeerAddr(const struct sockaddr *dst_addr, socklen_t addr_len = 0);
 
     /**
      * 设置发送flags
      * @param flags 发送的flag
      */
-    void setSendFlags(int flags = SOCKET_DEFAULE_FLAGS);
+    virtual void setSendFlags(int flags = SOCKET_DEFAULE_FLAGS);
 
     /**
      * 关闭套接字
-     * @param close_fd 是否关闭fd还是只移除io事件监听
      */
-    void closeSock(bool close_fd = true);
+    virtual void closeSock();
 
     /**
      * 获取发送缓存包个数(不是字节数)
      */
-    size_t getSendBufferCount();
+    virtual size_t getSendBufferCount();
 
     /**
      * 获取上次socket发送缓存清空至今的毫秒数,单位毫秒
      */
-    uint64_t elapsedTimeAfterFlushed();
-
-    /**
-     * 获取接收速率,单位bytes/s
-     */
-    int getRecvSpeed();
-
-    /**
-     * 获取发送速率,单位bytes/s
-     */
-    int getSendSpeed();
+    virtual uint64_t elapsedTimeAfterFlushed();
 
     ////////////SockInfo override////////////
-    std::string get_local_ip() override;
+    string get_local_ip() override;
     uint16_t get_local_port() override;
-    std::string get_peer_ip() override;
+    string get_peer_ip() override;
     uint16_t get_peer_port() override;
-    std::string getIdentifier() const override;
+    string getIdentifier() const override;
 
 private:
-    SockFD::Ptr cloneSockFD(const Socket &other);
+    SockFD::Ptr setPeerSock(int fd);
     SockFD::Ptr makeSock(int sock, SockNum::SockType type);
-    void setPeerSock(int fd, SockNum::SockType type);
-    int onAccept(int sock, int event) noexcept;
-    ssize_t onRead(int sock, SockNum::SockType type, const BufferRaw::Ptr &buffer) noexcept;
-    void onWriteAble(int sock, SockNum::SockType type);
-    void onConnected(int sock, const onErrCB &cb);
-    void onFlushed();
-    void startWriteAbleEvent(int sock);
-    void stopWriteAbleEvent(int sock);
+    int onAccept(const SockFD::Ptr &sock, int event) noexcept;
+    ssize_t onRead(const SockFD::Ptr &sock, bool is_udp = false) noexcept;
+    void onWriteAble(const SockFD::Ptr &sock);
+    void onConnected(const SockFD::Ptr &sock, const onErrCB &cb);
+    void onFlushed(const SockFD::Ptr &pSock);
+    void startWriteAbleEvent(const SockFD::Ptr &sock);
+    void stopWriteAbleEvent(const SockFD::Ptr &sock);
     bool listen(const SockFD::Ptr &sock);
-    bool flushData(int sock, SockNum::SockType type, bool poller_thread);
-    bool attachEvent(int sock, SockNum::SockType type);
+    bool flushData(const SockFD::Ptr &sock, bool poller_thread);
+    bool attachEvent(const SockFD::Ptr &sock, bool is_udp = false);
     ssize_t send_l(Buffer::Ptr buf, bool is_buf_sock, bool try_flush = true);
-    void connect_l(const std::string &url, uint16_t port, const onErrCB &con_cb_in, float timeout_sec, const std::string &local_ip, uint16_t local_port);
-    bool fromSock_l(int fd, SockNum::SockType type);
 
 private:
     //send socket时的flag
@@ -521,31 +470,25 @@ private:
     //最大发送缓存,单位毫秒,距上次发送缓存清空时间不能超过该参数
     uint32_t _max_send_buffer_ms = SEND_TIME_OUT_SEC * 1000;
     //控制是否接收监听socket可读事件,关闭后可用于流量控制
-    std::atomic<bool> _enable_recv {true};
+    atomic<bool> _enable_recv {true};
     //标记该socket是否可写,socket写缓存满了就不可写
-    std::atomic<bool> _sendable {true};
-    //是否已经触发err回调了
-    bool _err_emit = false;
-    //是否启用网速统计
-    bool _enable_speed = false;
-    //接收速率统计
-    BytesSpeed _recv_speed;
-    //发送速率统计
-    BytesSpeed _send_speed;
+    atomic<bool> _sendable {true};
 
     //tcp连接超时定时器
     Timer::Ptr _con_timer;
     //tcp连接结果回调对象
-    std::shared_ptr<std::function<void(int)> > _async_con_cb;
+    std::shared_ptr<function<void(int)> > _async_con_cb;
 
     //记录上次发送缓存(包括socket写缓存、应用层缓存)清空的计时器
     Ticker _send_flush_ticker;
+    //复用的socket读缓存,每次read socket后,数据存放在此
+    BufferRaw::Ptr _read_buffer;
     //socket fd的抽象类
     SockFD::Ptr _sock_fd;
     //本socket绑定的poller线程,事件触发于此线程
     EventPoller::Ptr _poller;
     //跨线程访问_sock_fd时需要上锁
-    mutable MutexWrapper<std::recursive_mutex> _mtx_sock_fd;
+    mutable MutexWrapper<recursive_mutex> _mtx_sock_fd;
 
     //socket异常事件(比如说断开)
     onErrCB _on_err;
@@ -558,16 +501,16 @@ private:
     //tcp监听收到accept请求,自定义创建peer Socket事件(可以控制子Socket绑定到其他poller线程)
     onCreateSocket _on_before_accept;
     //设置上述回调函数的锁
-    MutexWrapper<std::recursive_mutex> _mtx_event;
+    MutexWrapper<recursive_mutex> _mtx_event;
 
     //一级发送缓存, socket可写时,会把一级缓存批量送入到二级缓存
     List<std::pair<Buffer::Ptr, bool> > _send_buf_waiting;
     //一级发送缓存锁
-    MutexWrapper<std::recursive_mutex> _mtx_send_buf_waiting;
+    MutexWrapper<recursive_mutex> _mtx_send_buf_waiting;
     //二级发送缓存, socket可写时,会把二级缓存批量写入到socket
     List<BufferList::Ptr> _send_buf_sending;
     //二级发送缓存锁
-    MutexWrapper<std::recursive_mutex> _mtx_send_buf_sending;
+    MutexWrapper<recursive_mutex> _mtx_send_buf_sending;
     //发送buffer结果回调
     BufferList::SendResult _send_result;
     //对象个数统计
@@ -584,31 +527,30 @@ public:
     //发送char *
     SockSender &operator << (const char *buf);
     //发送字符串
-    SockSender &operator << (std::string buf);
+    SockSender &operator << (string buf);
     //发送Buffer对象
     SockSender &operator << (Buffer::Ptr buf);
 
     //发送其他类型是数据
     template<typename T>
     SockSender &operator << (T &&buf) {
-        std::ostringstream ss;
+        ostringstream ss;
         ss << std::forward<T>(buf);
         send(ss.str());
         return *this;
     }
 
-    ssize_t send(std::string buf);
+    ssize_t send(string buf);
     ssize_t send(const char *buf, size_t size = 0);
 };
 
 //Socket对象的包装类
-class SocketHelper : public SockSender, public SockInfo, public TaskExecutorInterface, public std::enable_shared_from_this<SocketHelper> {
+class SocketHelper : public SockSender, public SockInfo, public TaskExecutorInterface {
 public:
-    using Ptr = std::shared_ptr<SocketHelper>;
     SocketHelper(const Socket::Ptr &sock);
-    ~SocketHelper() override = default;
+    ~SocketHelper() override;
 
-    ///////////////////// Socket util std::functions /////////////////////
+    ///////////////////// Socket util functions /////////////////////
     /**
      * 获取poller线程
      */
@@ -642,26 +584,10 @@ public:
      */
     Socket::Ptr createSocket();
 
-    /**
-     * 获取socket对象
-     */
-    const Socket::Ptr &getSock() const;
-
-    /**
-     * 尝试将所有数据写socket
-     * @return -1代表失败(socket无效或者发送超时),0代表成功?
-     */
-    int flushAll();
-
-    /**
-     * 是否ssl加密
-     */
-    virtual bool overSsl() const { return false; }
-
     ///////////////////// SockInfo override /////////////////////
-    std::string get_local_ip() override;
+    string get_local_ip() override;
     uint16_t get_local_port() override;
-    std::string get_peer_ip() override;
+    string get_peer_ip() override;
     uint16_t get_peer_port() override;
 
     ///////////////////// TaskExecutorInterface override /////////////////////
@@ -684,42 +610,17 @@ public:
      */
     void shutdown(const SockException &ex = SockException(Err_shutdown, "self shutdown")) override;
 
-    /**
-     * 线程安全的脱离 Server 并触发 onError 事件
-     * @param ex 触发 onError 事件的原因
-     */
-    void safeShutdown(const SockException &ex = SockException(Err_shutdown, "self shutdown"));
-
-    ///////////////////// event functions /////////////////////
-    /**
-     * 接收数据入口
-     * @param buf 数据,可以重复使用内存区,不可被缓存使用
-     */
-    virtual void onRecv(const Buffer::Ptr &buf) = 0;
-
-    /**
-     * 收到 eof 或其他导致脱离 Server 事件的回调
-     * 收到该事件时, 该对象一般将立即被销毁
-     * @param err 原因
-     */
-    virtual void onError(const SockException &err) = 0;
-
-    /**
-     * 数据全部发送完毕后回调
-     */
-    virtual void onFlush() {}
-
-    /**
-     * 每隔一段时间触发, 用来做超时管理
-     */
-    virtual void onManager() = 0;
-
 protected:
     void setPoller(const EventPoller::Ptr &poller);
     void setSock(const Socket::Ptr &sock);
+    const Socket::Ptr& getSock() const;
 
 private:
     bool _try_flush = true;
+    uint16_t _peer_port = 0;
+    uint16_t _local_port = 0;
+    string _peer_ip;
+    string _local_ip;
     Socket::Ptr _sock;
     EventPoller::Ptr _poller;
     Socket::onCreateSocket _on_create_socket;

+ 40 - 47
3rdparty/ZLToolKit/include/Network/TcpClient.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,16 +11,20 @@
 #ifndef NETWORK_TCPCLIENT_H
 #define NETWORK_TCPCLIENT_H
 
+#include <mutex>
 #include <memory>
+#include <functional>
 #include "Socket.h"
+#include "Util/TimeTicker.h"
 #include "Util/SSLBox.h"
+using namespace std;
 
 namespace toolkit {
 
 //Tcp客户端,Socket对象默认开始互斥锁
-class TcpClient : public SocketHelper {
+class TcpClient : public std::enable_shared_from_this<TcpClient>, public SocketHelper {
 public:
-    using Ptr = std::shared_ptr<TcpClient>;
+    typedef std::shared_ptr<TcpClient> Ptr;
     TcpClient(const EventPoller::Ptr &poller = nullptr);
     ~TcpClient() override;
 
@@ -29,20 +33,9 @@ public:
      * @param url 服务器ip或域名
      * @param port 服务器端口
      * @param timeout_sec 超时时间,单位秒
-     * @param local_port 本地端口
      */
-    virtual void startConnect(const std::string &url, uint16_t port, float timeout_sec = 5, uint16_t local_port = 0);
-    
-    /**
-     * 通过代理开始连接tcp服务器
-     * @param url 服务器ip或域名
-     * @proxy_host 代理ip
-     * @proxy_port 代理端口
-     * @param timeout_sec 超时时间,单位秒
-     * @param local_port 本地端口
-     */
-    virtual void startConnectWithProxy(const std::string &url, const std::string &proxy_host, uint16_t proxy_port, float timeout_sec = 5, uint16_t local_port = 0){};
-    
+    virtual void startConnect(const string &url, uint16_t port, float timeout_sec = 5);
+
     /**
      * 主动断开连接
      * @param ex 触发onErr事件时的参数
@@ -50,39 +43,50 @@ public:
     void shutdown(const SockException &ex = SockException(Err_shutdown, "self shutdown")) override;
 
     /**
-     * 连接中或已连接返回true,断开连接时返回false
+     * 判断是否与服务器连接中
      */
-    virtual bool alive() const;
+    virtual bool alive();
 
     /**
      * 设置网卡适配器,使用该网卡与服务器通信
      * @param local_ip 本地网卡ip
      */
-    virtual void setNetAdapter(const std::string &local_ip);
-
-    /**
-     * 唯一标识
-     */
-    std::string getIdentifier() const override;
+    virtual void setNetAdapter(const string &local_ip);
 
 protected:
     /**
      * 连接服务器结果回调
      * @param ex 成功与否
      */
-    virtual void onConnect(const SockException &ex) = 0;
+    virtual void onConnect(const SockException &ex) {}
+
+    /**
+     * 收到数据回调
+     * @param buf 接收到的数据(该buffer会重复使用)
+     */
+    virtual void onRecv(const Buffer::Ptr &buf) {}
+
+    /**
+     * 数据全部发送完毕后回调
+     */
+    virtual void onFlush() {}
+
+    /**
+     * 被动断开连接回调
+     * @param ex 断开原因
+     */
+    virtual void onErr(const SockException &ex) {}
 
     /**
      * tcp连接成功后每2秒触发一次该事件
      */
-    void onManager() override {}
+    virtual void onManager() {}
 
 private:
     void onSockConnect(const SockException &ex);
 
 private:
-    mutable std::string _id;
-    std::string _net_adapter = "::";
+    string _net_adapter = "0.0.0.0";
     std::shared_ptr<Timer> _timer;
     //对象个数统计
     ObjectStatistic<TcpClient> _statistic;
@@ -90,14 +94,14 @@ private:
 
 //用于实现TLS客户端的模板对象
 template<typename TcpClientType>
-class TcpClientWithSSL : public TcpClientType {
+class TcpClientWithSSL: public TcpClientType {
 public:
-    using Ptr = std::shared_ptr<TcpClientWithSSL>;
+    typedef std::shared_ptr<TcpClientWithSSL> Ptr;
 
     template<typename ...ArgsType>
     TcpClientWithSSL(ArgsType &&...args):TcpClientType(std::forward<ArgsType>(args)...) {}
 
-    ~TcpClientWithSSL() override {
+    ~TcpClientWithSSL() override{
         if (_ssl_box) {
             _ssl_box->flush();
         }
@@ -114,7 +118,7 @@ public:
     ssize_t send(Buffer::Ptr buf) override {
         if (_ssl_box) {
             auto size = buf->size();
-            _ssl_box->onSend(std::move(buf));
+            _ssl_box->onSend(buf);
             return size;
         }
         return TcpClientType::send(std::move(buf));
@@ -129,17 +133,11 @@ public:
         TcpClientType::send(std::move(const_cast<Buffer::Ptr &>(buf)));
     }
 
-    void startConnect(const std::string &url, uint16_t port, float timeout_sec = 5, uint16_t local_port = 0) override {
-        _host = url;
-        TcpClientType::startConnect(url, port, timeout_sec, local_port);
-    }
-    void startConnectWithProxy(const std::string &url, const std::string &proxy_host, uint16_t proxy_port, float timeout_sec = 5, uint16_t local_port = 0) override {
+    void startConnect(const string &url, uint16_t port, float timeout_sec = 5) override {
         _host = url;
-        TcpClientType::startConnect(proxy_host, proxy_port, timeout_sec, local_port);
+        TcpClientType::startConnect(url, port, timeout_sec);
     }
 
-    bool overSsl() const override { return (bool)_ssl_box; }
-
 protected:
     void onConnect(const SockException &ex) override {
         if (!ex) {
@@ -158,14 +156,9 @@ protected:
         }
         TcpClientType::onConnect(ex);
     }
-    /**
-     * 重置ssl, 主要为了解决一些302跳转时http与https的转换
-     */
-    void setDoNotUseSSL() {
-        _ssl_box.reset();
-    }
+
 private:
-    std::string _host;
+    string _host;
     std::shared_ptr<SSL_Box> _ssl_box;
 };
 

+ 22 - 25
3rdparty/ZLToolKit/include/Network/TcpServer.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,17 +11,26 @@
 #ifndef TCPSERVER_TCPSERVER_H
 #define TCPSERVER_TCPSERVER_H
 
+#include <assert.h>
+#include <mutex>
 #include <memory>
+#include <exception>
 #include <functional>
 #include <unordered_map>
-#include "Server.h"
-#include "Session.h"
+
+#include "Network/Server.h"
+#include "Network/TcpSession.h"
 #include "Poller/Timer.h"
+#include "Thread/semaphore.h"
+#include "Util/logger.h"
 #include "Util/util.h"
+#include "Util/uv_errno.h"
+
+using namespace std;
 
 namespace toolkit {
 
-//TCP服务器,可配置的;配置通过Session::attachServer方法传递给会话对象
+//TCP服务器,可配置的;配置通过TcpSession::attachServer方法传递给会话对象
 class TcpServer : public Server {
 public:
     using Ptr = std::shared_ptr<TcpServer>;
@@ -42,18 +51,13 @@ public:
     * @param host 监听网卡ip
     * @param backlog tcp listen backlog
     */
-    template<typename SessionType>
-    void start(uint16_t port, const std::string &host = "::", uint32_t backlog = 1024) {
-        static std::string cls_name = toolkit::demangle(typeid(SessionType).name());
-        //Session创建器,通过它创建不同类型的服务器
+    template <typename SessionType>
+    void start(uint16_t port, const std::string &host = "0.0.0.0", uint32_t backlog = 1024) {
+        //TcpSession创建器,通过它创建不同类型的服务器
         _session_alloc = [](const TcpServer::Ptr &server, const Socket::Ptr &sock) {
-            auto session = std::shared_ptr<SessionType>(new SessionType(sock), [](SessionType * ptr) {
-                TraceP(static_cast<Session *>(ptr)) << "~" << cls_name;
-                delete ptr;
-            });
-            TraceP(static_cast<Session *>(session.get())) << cls_name;
+            auto session = std::make_shared<SessionType>(sock);
             session->setOnCreateSocket(server->_on_create_socket);
-            return std::make_shared<SessionHelper>(server, std::move(session), cls_name);
+            return std::make_shared<SessionHelper>(server, session);
         };
         start_l(port, host, backlog);
     }
@@ -68,17 +72,11 @@ public:
      */
     void setOnCreateSocket(Socket::onCreateSocket cb);
 
-    /**
-     * 根据socket对象创建Session对象
-     * 需要确保在socket归属poller线程执行本函数
-     */
-    Session::Ptr createSession(const Socket::Ptr &socket);
-
 protected:
     virtual void cloneFrom(const TcpServer &that);
     virtual TcpServer::Ptr onCreatServer(const EventPoller::Ptr &poller);
 
-    virtual Session::Ptr onAcceptConnection(const Socket::Ptr &sock);
+    virtual void onAcceptConnection(const Socket::Ptr &sock);
     virtual Socket::Ptr onBeforeAcceptConnection(const EventPoller::Ptr &poller);
 
 private:
@@ -86,7 +84,6 @@ private:
     Socket::Ptr createSocket(const EventPoller::Ptr &poller);
     void start_l(uint16_t port, const std::string &host, uint32_t backlog);
     Ptr getServer(const EventPoller *) const;
-    void setupEvent();
 
 private:
     bool _is_on_manager = false;
@@ -94,9 +91,9 @@ private:
     Socket::Ptr _socket;
     std::shared_ptr<Timer> _timer;
     Socket::onCreateSocket _on_create_socket;
-    std::unordered_map<SessionHelper *, SessionHelper::Ptr> _session_map;
-    std::function<SessionHelper::Ptr(const TcpServer::Ptr &server, const Socket::Ptr &)> _session_alloc;
-    std::unordered_map<const EventPoller *, Ptr> _cloned_server;
+    unordered_map<SessionHelper *, SessionHelper::Ptr> _session_map;
+    function<SessionHelper::Ptr(const TcpServer::Ptr &server, const Socket::Ptr &)> _session_alloc;
+    unordered_map<const EventPoller *, Ptr> _cloned_server;
     //对象个数统计
     ObjectStatistic<TcpServer> _statistic;
 };

+ 65 - 0
3rdparty/ZLToolKit/include/Network/TcpSession.h

@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
+ *
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
+ *
+ * Use of this source code is governed by MIT license that can be found in the
+ * LICENSE file in the root of the source tree. All contributing project authors
+ * may be found in the AUTHORS file in the root of the source tree.
+ */
+
+#ifndef SERVER_SESSION_H_
+#define SERVER_SESSION_H_
+
+#include "Util/SSLBox.h"
+#include "Network/Session.h"
+
+using namespace std;
+
+namespace toolkit {
+
+//通过该模板可以让TCP服务器快速支持TLS
+template<typename TcpSessionType>
+class TcpSessionWithSSL : public TcpSessionType {
+public:
+    template<typename ...ArgsType>
+    TcpSessionWithSSL(ArgsType &&...args):TcpSessionType(std::forward<ArgsType>(args)...) {
+        _ssl_box.setOnEncData([&](const Buffer::Ptr &buf) {
+            public_send(buf);
+        });
+        _ssl_box.setOnDecData([&](const Buffer::Ptr &buf) {
+            public_onRecv(buf);
+        });
+    }
+
+    ~TcpSessionWithSSL() override{
+        _ssl_box.flush();
+    }
+
+    void onRecv(const Buffer::Ptr &buf) override {
+        _ssl_box.onRecv(buf);
+    }
+
+    //添加public_onRecv和public_send函数是解决较低版本gcc一个lambad中不能访问protected或private方法的bug
+    inline void public_onRecv(const Buffer::Ptr &buf) {
+        TcpSessionType::onRecv(buf);
+    }
+
+    inline void public_send(const Buffer::Ptr &buf) {
+        TcpSessionType::send(std::move(const_cast<Buffer::Ptr &>(buf)));
+    }
+
+protected:
+    ssize_t send(Buffer::Ptr buf) override {
+        auto size = buf->size();
+        _ssl_box.onSend(buf);
+        return size;
+    }
+
+private:
+    SSL_Box _ssl_box;
+};
+
+} /* namespace toolkit */
+
+#endif /* SERVER_SESSION_H_ */

+ 14 - 25
3rdparty/ZLToolKit/include/Network/UdpServer.h

@@ -11,16 +11,15 @@
 #ifndef TOOLKIT_NETWORK_UDPSERVER_H
 #define TOOLKIT_NETWORK_UDPSERVER_H
 
-#include "Server.h"
-#include "Session.h"
+#include "Network/Server.h"
+#include "Network/Session.h"
 
 namespace toolkit {
 
 class UdpServer : public Server {
 public:
     using Ptr = std::shared_ptr<UdpServer>;
-    using PeerIdType = std::string;
-    using onCreateSocket = std::function<Socket::Ptr(const EventPoller::Ptr &, const Buffer::Ptr &, struct sockaddr *, int)>;
+    using PeerIdType = uint64_t;
 
     explicit UdpServer(const EventPoller::Ptr &poller = nullptr);
     ~UdpServer() override;
@@ -29,20 +28,12 @@ public:
      * @brief 开始监听服务器
      */
     template<typename SessionType>
-    void start(uint16_t port, const std::string &host = "::") {
-        static std::string cls_name = toolkit::demangle(typeid(SessionType).name());
+    void start(uint16_t port, const std::string &host = "0.0.0.0") {
         // Session 创建器, 通过它创建不同类型的服务器
         _session_alloc = [](const UdpServer::Ptr &server, const Socket::Ptr &sock) {
-            auto session = std::shared_ptr<SessionType>(new SessionType(sock), [](SessionType * ptr) {
-                TraceP(static_cast<Session *>(ptr)) << "~" << cls_name;
-                delete ptr;
-            });
-            TraceP(static_cast<Session *>(session.get())) << cls_name;
-            auto sock_creator = server->_on_create_socket;
-            session->setOnCreateSocket([sock_creator](const EventPoller::Ptr &poller) {
-                return sock_creator(poller, nullptr, nullptr, 0);
-            });
-            return std::make_shared<SessionHelper>(server, std::move(session), cls_name);
+            auto session = std::make_shared<SessionType>(sock);
+            session->setOnCreateSocket(server->_on_create_socket);
+            return std::make_shared<SessionHelper>(server, session);
         };
         start_l(port, host);
     }
@@ -55,7 +46,7 @@ public:
     /**
      * @brief 自定义socket构建行为
      */
-    void setOnCreateSocket(onCreateSocket cb);
+    void setOnCreateSocket(Socket::onCreateSocket cb);
 
 protected:
     virtual Ptr onCreatServer(const EventPoller::Ptr &poller);
@@ -67,7 +58,7 @@ private:
      * @param port 本机端口,0则随机
      * @param host 监听网卡ip
      */
-    void start_l(uint16_t port, const std::string &host = "::");
+    void start_l(uint16_t port, const std::string &host = "0.0.0.0");
 
     /**
      * @brief 定时管理 Session, UDP 会话需要根据需要处理超时
@@ -89,31 +80,29 @@ private:
     /**
      * @brief 根据对端信息获取或创建一个会话
      */
-    Session::Ptr getOrCreateSession(const PeerIdType &id, const Buffer::Ptr &buf, struct sockaddr *addr, int addr_len, bool &is_new);
+    const Session::Ptr& getOrCreateSession(const PeerIdType &id, struct sockaddr *addr, int addr_len, bool &is_new);
 
     /**
      * @brief 创建一个会话, 同时进行必要的设置
      */
-    Session::Ptr createSession(const PeerIdType &id, const Buffer::Ptr &buf, struct sockaddr *addr, int addr_len);
+    const Session::Ptr& createSession(const PeerIdType &id, struct sockaddr *addr, int addr_len);
 
     /**
      * @brief 创建socket
      */
-    Socket::Ptr createSocket(const EventPoller::Ptr &poller, const Buffer::Ptr &buf = nullptr, struct sockaddr *addr = nullptr, int addr_len = 0);
-
-    void setupEvent();
+    Socket::Ptr createSocket(const EventPoller::Ptr &poller);
 
 private:
     bool _cloned = false;
     Socket::Ptr _socket;
     std::shared_ptr<Timer> _timer;
-    onCreateSocket _on_create_socket;
+    Socket::onCreateSocket _on_create_socket;
     //cloned server共享主server的session map,防止数据在不同server间漂移
     std::shared_ptr<std::recursive_mutex> _session_mutex;
     std::shared_ptr<std::unordered_map<PeerIdType, SessionHelper::Ptr> > _session_map;
     //主server持有cloned server的引用
     std::unordered_map<EventPoller *, Ptr> _cloned_server;
-    std::function<SessionHelper::Ptr(const UdpServer::Ptr &, const Socket::Ptr &)> _session_alloc;
+    std::function<SessionHelper::Ptr(const UdpServer::Ptr&, const Socket::Ptr&)> _session_alloc;
     // 对象个数统计
     ObjectStatistic<UdpServer> _statistic;
 };

+ 89 - 96
3rdparty/ZLToolKit/include/Network/sockutil.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -14,7 +14,7 @@
 #if defined(_WIN32)
 #include <winsock2.h>
 #include <ws2tcpip.h>
-#include <iphlpapi.h>
+#include <Iphlpapi.h>
 #pragma comment (lib, "Ws2_32.lib")
 #pragma comment(lib,"Iphlpapi.lib")
 #else
@@ -27,11 +27,12 @@
 #include <netinet/tcp.h>
 #endif // defined(_WIN32)
 
-#include <cstring>
-#include <cstdint>
 #include <map>
 #include <vector>
 #include <string>
+#include <string.h>
+#include <stdint.h>
+using namespace std;
 
 namespace toolkit {
 
@@ -47,9 +48,6 @@ int close(int fd);
 #endif // defined(_WIN32)
 
 #define SOCKET_DEFAULT_BUF_SIZE (256 * 1024)
-#define TCP_KEEPALIVE_INTERVAL 30
-#define TCP_KEEPALIVE_PROBE_TIMES 9
-#define TCP_KEEPALIVE_TIME 120
 
 //套接字工具类,封装了socket、网络的一些基本操作
 class SockUtil {
@@ -58,30 +56,38 @@ public:
      * 创建tcp客户端套接字并连接服务器
      * @param host 服务器ip或域名
      * @param port 服务器端口号
-     * @param async 是否异步连接
-     * @param local_ip 绑定的本地网卡ip
-     * @param local_port 绑定的本地端口号
+     * @param bAsync 是否异步连接
+     * @param localIp 绑定的本地网卡ip
+     * @param localPort 绑定的本地端口号
      * @return -1代表失败,其他为socket fd号
      */
-    static int connect(const char *host, uint16_t port, bool async = true, const char *local_ip = "::", uint16_t local_port = 0);
+    static int connect(const char *host, uint16_t port, bool bAsync = true,const char *localIp = "0.0.0.0",uint16_t localPort = 0);
 
     /**
      * 创建tcp监听套接字
      * @param port 监听的本地端口
-     * @param local_ip 绑定的本地网卡ip
-     * @param back_log accept列队长度
+     * @param localIp 绑定的本地网卡ip
+     * @param backLog accept列队长度
      * @return -1代表失败,其他为socket fd号
      */
-    static int listen(const uint16_t port, const char *local_ip = "::", int back_log = 1024);
+    static int listen(const uint16_t port, const char *localIp = "0.0.0.0", int backLog = 1024);
 
     /**
      * 创建udp套接字
      * @param port 监听的本地端口
-     * @param local_ip 绑定的本地网卡ip
-     * @param enable_reuse 是否允许重复bind端口
+     * @param localIp 绑定的本地网卡ip
      * @return -1代表失败,其他为socket fd号
      */
-    static int bindUdpSock(const uint16_t port, const char *local_ip = "::", bool enable_reuse = true);
+    static int bindUdpSock(const uint16_t port, const char *localIp = "0.0.0.0");
+
+    /**
+     * @brief 初始化套接字 sock 连接关系
+     * @param sock, socket fd 号
+     * @param addr, 对端地址
+     * @param addr_len
+     * @return 0 成功, -1 失败
+     */
+    static int connectUdpSock(int sock, struct sockaddr *addr, int addr_len);
 
     /**
      * @brief 解除与 sock 相关的绑定关系
@@ -91,72 +97,78 @@ public:
     static int dissolveUdpSock(int sock);
 
     /**
+     * 绑定socket fd至某个网卡和端口
+     * @param sock socket fd号
+     * @param localIp 绑定的本地网卡ip
+     * @param port 绑定的本地端口
+     * @return 0代表成功,-1为失败
+     */
+    static int bindSock(int sock,const char *localIp,uint16_t port);
+
+    /**
      * 开启TCP_NODELAY,降低TCP交互延时
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param on 是否开启
      * @return 0代表成功,-1为失败
      */
-    static int setNoDelay(int fd, bool on = true);
+    static int setNoDelay(int sock, bool on = true);
 
     /**
      * 写socket不触发SIG_PIPE信号(貌似只有mac有效)
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @return 0代表成功,-1为失败
      */
-    static int setNoSigpipe(int fd);
+    static int setNoSigpipe(int sock);
 
     /**
      * 设置读写socket是否阻塞
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param noblock 是否阻塞
      * @return 0代表成功,-1为失败
      */
-    static int setNoBlocked(int fd, bool noblock = true);
+    static int setNoBlocked(int sock, bool noblock = true);
 
     /**
      * 设置socket接收缓存,默认貌似8K左右,一般有设置上限
      * 可以通过配置内核配置文件调整
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param size 接收缓存大小
      * @return 0代表成功,-1为失败
      */
-    static int setRecvBuf(int fd, int size = SOCKET_DEFAULT_BUF_SIZE);
+    static int setRecvBuf(int sock, int size = SOCKET_DEFAULT_BUF_SIZE);
 
     /**
      * 设置socket接收缓存,默认貌似8K左右,一般有设置上限
      * 可以通过配置内核配置文件调整
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param size 接收缓存大小
      * @return 0代表成功,-1为失败
      */
-    static int setSendBuf(int fd, int size = SOCKET_DEFAULT_BUF_SIZE);
+    static int setSendBuf(int sock, int size = SOCKET_DEFAULT_BUF_SIZE);
 
     /**
      * 设置后续可绑定复用端口(处于TIME_WAITE状态)
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param on 是否开启该特性
      * @return 0代表成功,-1为失败
      */
-    static int setReuseable(int fd, bool on = true, bool reuse_port = true);
+    static int setReuseable(int sock, bool on = true, bool reuse_port = true);
 
     /**
      * 运行发送或接收udp广播信息
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param on 是否开启该特性
      * @return 0代表成功,-1为失败
      */
-    static int setBroadcast(int fd, bool on = true);
+    static int setBroadcast(int sock, bool on = true);
 
     /**
      * 是否开启TCP KeepAlive特性
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @param on 是否开启该特性
-     * @param idle keepalive空闲时间
-     * @param interval keepalive探测时间间隔
-     * @param times keepalive探测次数
      * @return 0代表成功,-1为失败
      */
-    static int setKeepAlive(int fd, bool on = true, int interval = TCP_KEEPALIVE_INTERVAL, int idle = TCP_KEEPALIVE_TIME, int times = TCP_KEEPALIVE_PROBE_TIMES);
+    static int setKeepAlive(int sock, bool on = true);
 
     /**
      * 是否开启FD_CLOEXEC特性(多进程相关)
@@ -181,8 +193,7 @@ public:
      * @param addr sockaddr结构体
      * @return 是否成功
      */
-    static bool getDomainIP(const char *host, uint16_t port, struct sockaddr_storage &addr, int ai_family = AF_INET,
-                            int ai_socktype = SOCK_STREAM, int ai_protocol = IPPROTO_TCP, int expire_sec = 60);
+    static bool getDomainIP(const char *host,uint16_t port,struct sockaddr &addr);
 
     /**
      * 设置组播ttl
@@ -195,80 +206,80 @@ public:
     /**
      * 设置组播发送网卡
      * @param sock socket fd号
-     * @param local_ip 本机网卡ip
+     * @param strLocalIp 本机网卡ip
      * @return 0代表成功,-1为失败
      */
-    static int setMultiIF(int sock, const char *local_ip);
+    static int setMultiIF(int sock, const char *strLocalIp);
 
     /**
      * 设置是否接收本机发出的组播包
-     * @param fd socket fd号
-     * @param acc 是否接收
+     * @param sock socket fd号
+     * @param bAccept 是否接收
      * @return 0代表成功,-1为失败
      */
-    static int setMultiLOOP(int fd, bool acc = false);
+    static int setMultiLOOP(int sock, bool bAccept = false);
 
     /**
      * 加入组播
-     * @param fd socket fd号
-     * @param addr 组播地址
-     * @param local_ip 本机网卡ip
+     * @param sock socket fd号
+     * @param strAddr 组播地址
+     * @param strLocalIp 本机网卡ip
      * @return 0代表成功,-1为失败
      */
-    static int joinMultiAddr(int fd, const char *addr, const char *local_ip = "0.0.0.0");
+    static int joinMultiAddr(int sock, const char *strAddr, const char* strLocalIp = "0.0.0.0");
 
     /**
      * 退出组播
-     * @param fd socket fd号
-     * @param addr 组播地址
-     * @param local_ip 本机网卡ip
+     * @param sock socket fd号
+     * @param strAddr 组播地址
+     * @param strLocalIp 本机网卡ip
      * @return 0代表成功,-1为失败
      */
-    static int leaveMultiAddr(int fd, const char *addr, const char *local_ip = "0.0.0.0");
+    static int leaveMultiAddr(int sock, const char *strAddr, const char* strLocalIp = "0.0.0.0");
 
     /**
      * 加入组播并只接受该源端的组播数据
      * @param sock socket fd号
-     * @param addr 组播地址
-     * @param src_ip 数据源端地址
-     * @param local_ip  本机网卡ip
+     * @param strAddr 组播地址
+     * @param strSrcIp 数据源端地址
+     * @param strLocalIp  本机网卡ip
      * @return 0代表成功,-1为失败
      */
-    static int joinMultiAddrFilter(int sock, const char *addr, const char *src_ip, const char *local_ip = "0.0.0.0");
+    static int joinMultiAddrFilter(int sock, const char* strAddr, const char* strSrcIp, const char* strLocalIp = "0.0.0.0");
 
     /**
      * 退出组播
-     * @param fd socket fd号
-     * @param addr 组播地址
-     * @param src_ip 数据源端地址
-     * @param local_ip  本机网卡ip
+     * @param sock socket fd号
+     * @param strAddr 组播地址
+     * @param strSrcIp 数据源端地址
+     * @param strLocalIp  本机网卡ip
      * @return 0代表成功,-1为失败
      */
-    static int leaveMultiAddrFilter(int fd, const char *addr, const char *src_ip, const char *local_ip = "0.0.0.0");
+    static int leaveMultiAddrFilter(int sock, const char* strAddr, const char* strSrcIp, const char* strLocalIp = "0.0.0.0");
 
     /**
      * 获取该socket当前发生的错误
-     * @param fd socket fd号
+     * @param sock socket fd号
      * @return 错误代码
      */
-    static int getSockError(int fd);
+    static int getSockError(int sock);
 
     /**
      * 获取网卡列表
      * @return vector<map<ip:name> >
      */
-    static std::vector<std::map<std::string, std::string>> getInterfaceList();
+    static vector<map<string,string> > getInterfaceList();
 
     /**
      * 获取本机默认网卡ip
      */
-    static std::string get_local_ip();
+    static string get_local_ip();
 
     /**
      * 获取该socket绑定的本地ip
      * @param sock socket fd号
      */
-    static std::string get_local_ip(int sock);
+    static string get_local_ip(int sock);
 
     /**
      * 获取该socket绑定的本地端口
@@ -280,7 +291,7 @@ public:
      * 获取该socket绑定的远端ip
      * @param sock socket fd号
      */
-    static std::string get_peer_ip(int sock);
+    static string get_peer_ip(int sock);
 
     /**
      * 获取该socket绑定的远端端口
@@ -288,59 +299,41 @@ public:
      */
     static uint16_t get_peer_port(int sock);
 
-    static bool support_ipv6();
     /**
      * 线程安全的in_addr转ip字符串
      */
-    static std::string inet_ntoa(const struct in_addr &addr);
-    static std::string inet_ntoa(const struct in6_addr &addr);
-    static std::string inet_ntoa(const struct sockaddr *addr);
-    static uint16_t inet_port(const struct sockaddr *addr);
-    static struct sockaddr_storage make_sockaddr(const char *ip, uint16_t port);
-    static socklen_t get_sock_len(const struct sockaddr *addr);
-    static bool get_sock_local_addr(int fd, struct sockaddr_storage &addr);
-    static bool get_sock_peer_addr(int fd, struct sockaddr_storage &addr);
+    static string inet_ntoa(struct in_addr &addr);
 
     /**
      * 获取网卡ip
-     * @param if_name 网卡名
+     * @param ifrName 网卡名
      */
-    static std::string get_ifr_ip(const char *if_name);
+    static string get_ifr_ip(const char *ifrName);
 
     /**
      * 获取网卡名
-     * @param local_op 网卡ip
+     * @param localIp 网卡ip
      */
-    static std::string get_ifr_name(const char *local_op);
+    static string get_ifr_name(const char *localIp);
 
     /**
      * 根据网卡名获取子网掩码
-     * @param if_name 网卡名
+     * @param ifrName 网卡名
      */
-    static std::string get_ifr_mask(const char *if_name);
+    static string get_ifr_mask(const char *ifrName);
 
     /**
      * 根据网卡名获取广播地址
-     * @param if_name 网卡名
+     * @param ifrName 网卡名
      */
-    static std::string get_ifr_brdaddr(const char *if_name);
+    static string get_ifr_brdaddr(const char *ifrName);
 
     /**
      * 判断两个ip是否为同一网段
-     * @param src_ip 我的ip
-     * @param dts_ip 对方ip
-     */
-    static bool in_same_lan(const char *src_ip, const char *dts_ip);
-
-    /**
-     * 判断是否为ipv4地址
-     */
-    static bool is_ipv4(const char *str);
-
-    /**
-     * 判断是否为ipv6地址
+     * @param myIp 我的ip
+     * @param dstIp 对方ip
      */
-    static bool is_ipv6(const char *str);
+    static bool in_same_lan(const char *myIp, const char *dstIp);
 };
 
 }  // namespace toolkit

+ 44 - 56
3rdparty/ZLToolKit/include/Poller/EventPoller.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -19,10 +19,12 @@
 #include <unordered_map>
 #include "PipeWrap.h"
 #include "Util/logger.h"
+#include "Util/util.h"
 #include "Util/List.h"
 #include "Thread/TaskExecutor.h"
 #include "Thread/ThreadPool.h"
 #include "Network/Buffer.h"
+using namespace std;
 
 #if defined(__linux__) || defined(__linux)
 #define HAS_EPOLL
@@ -30,21 +32,21 @@
 
 namespace toolkit {
 
+typedef enum {
+    Event_Read = 1 << 0, //读事件
+    Event_Write = 1 << 1, //写事件
+    Event_Error = 1 << 2, //错误事件
+    Event_LT = 1 << 3,//水平触发
+} Poll_Event;
+
+using PollEventCB = function<void(int event)>;
+using PollDelCB = function<void(bool success)>;
+using DelayTask = TaskCancelableImp<uint64_t(void)>;
+
 class EventPoller : public TaskExecutor, public AnyStorage, public std::enable_shared_from_this<EventPoller> {
 public:
-    friend class TaskExecutorGetterImp;
-
     using Ptr = std::shared_ptr<EventPoller>;
-    using PollEventCB = std::function<void(int event)>;
-    using PollDelCB = std::function<void(bool success)>;
-    using DelayTask = TaskCancelableImp<uint64_t(void)>;
-
-    typedef enum {
-        Event_Read = 1 << 0, //读事件
-        Event_Write = 1 << 1, //写事件
-        Event_Error = 1 << 2, //错误事件
-        Event_LT = 1 << 3,//水平触发
-    } Poll_Event;
+    friend class TaskExecutorGetterImp;
 
     ~EventPoller();
 
@@ -59,18 +61,18 @@ public:
      * 添加事件监听
      * @param fd 监听的文件描述符
      * @param event 事件类型,例如 Event_Read | Event_Write
-     * @param cb 事件回调functional
+     * @param eventCb 事件回调functional
      * @return -1:失败,0:成功
      */
-    int addEvent(int fd, int event, PollEventCB cb);
+    int addEvent(int fd, int event, PollEventCB eventCb);
 
     /**
      * 删除事件监听
      * @param fd 监听的文件描述符
-     * @param cb 删除成功回调functional
+     * @param delCb 删除成功回调functional
      * @return -1:失败,0:成功
      */
-    int delEvent(int fd, PollDelCB cb = nullptr);
+    int delEvent(int fd, PollDelCB delCb = nullptr);
 
     /**
      * 修改监听事件类型
@@ -86,7 +88,7 @@ public:
      * @param may_sync 如果调用该函数的线程就是本对象的轮询线程,那么may_sync为true时就是同步执行任务
      * @return 是否成功,一定会返回true
      */
-    Task::Ptr async(TaskIn task, bool may_sync = true) override;
+    Task::Ptr async(TaskIn task, bool may_sync = true) override ;
 
     /**
      * 同async方法,不过是把任务打入任务列队头,这样任务优先级最高
@@ -94,7 +96,7 @@ public:
      * @param may_sync 如果调用该函数的线程就是本对象的轮询线程,那么may_sync为true时就是同步执行任务
      * @return 是否成功,一定会返回true
      */
-    Task::Ptr async_first(TaskIn task, bool may_sync = true) override;
+    Task::Ptr async_first(TaskIn task, bool may_sync = true) override ;
 
     /**
      * 判断执行该接口的线程是否为本对象的轮询线程
@@ -104,11 +106,11 @@ public:
 
     /**
      * 延时执行某个任务
-     * @param delay_ms 延时毫秒数
+     * @param delayMS 延时毫秒数
      * @param task 任务,返回值为0时代表不再重复任务,否则为下次执行延时,如果任务中抛异常,那么默认不重复任务
      * @return 可取消的任务标签
      */
-    DelayTask::Ptr doDelayTask(uint64_t delay_ms, std::function<uint64_t()> task);
+    DelayTask::Ptr doDelayTask(uint64_t delayMS, function<uint64_t()> task);
 
     /**
      * 获取当前线程关联的Poller实例
@@ -123,25 +125,20 @@ public:
     /**
      * 获取poller线程id
      */
-    const std::thread::id& getThreadId() const;
-
-    /**
-     * 获取线程名
-     */
-    const std::string& getThreadName() const;
+    const thread::id& getThreadId() const;
 
 private:
     /**
      * 本对象只允许在EventPollerPool中构造
      */
-    EventPoller(std::string name, ThreadPool::Priority priority = ThreadPool::PRIORITY_HIGHEST);
+    EventPoller(ThreadPool::Priority priority = ThreadPool::PRIORITY_HIGHEST);
 
     /**
      * 执行事件轮询
      * @param blocked 是否用执行该接口的线程执行轮询
-     * @param ref_self 是记录本对象到thread local变量
+     * @param regist_self 是否注册到全局map
      */
-    void runLoop(bool blocked, bool ref_self);
+    void runLoop(bool blocked , bool regist_self);
 
     /**
      * 内部管道事件,用于唤醒轮询线程用
@@ -155,13 +152,13 @@ private:
      * @param first
      * @return 可取消的任务本体,如果已经同步执行,则返回nullptr
      */
-    Task::Ptr async_l(TaskIn task, bool may_sync = true, bool first = false);
+    Task::Ptr async_l(TaskIn task, bool may_sync = true,bool first = false) ;
 
     /**
      * 阻塞当前线程,等待轮询线程退出;
      * 在执行shutdown接口时本函数会退出
      */
-    void wait();
+    void wait() ;
 
     /**
      * 结束事件轮询
@@ -179,36 +176,33 @@ private:
      */
     uint64_t getMinDelay();
 
-    /**
-     * 添加管道监听事件
-     */
-    void addEventPipe();
-
 private:
-    class ExitException : public std::exception {};
+    class ExitException : public std::exception{
+    public:
+        ExitException(){}
+        ~ExitException(){}
+    };
 
 private:
     //标记loop线程是否退出
     bool _exit_flag;
-    //线程名
-    std::string _name;
     //当前线程下,所有socket共享的读缓存
-    std::weak_ptr<BufferRaw> _shared_buffer;
+    weak_ptr<BufferRaw> _shared_buffer;
     //线程优先级
     ThreadPool::Priority _priority;
     //正在运行事件循环时该锁处于被锁定状态
-    std::mutex _mtx_running;
+    mutex _mtx_runing;
     //执行事件循环的线程
-    std::thread *_loop_thread = nullptr;
+    thread *_loop_thread = nullptr;
     //事件循环的线程id
-    std::thread::id _loop_thread_id;
+    thread::id _loop_thread_id;
     //通知事件循环的线程已启动
     semaphore _sem_run_started;
 
     //内部事件管道
     PipeWrap _pipe;
     //从其他线程切换过来的任务
-    std::mutex _mtx_task;
+    mutex _mtx_task;
     List<Task::Ptr> _list_task;
 
     //保持日志可用
@@ -224,20 +218,19 @@ private:
         using Ptr = std::shared_ptr<Poll_Record>;
         int event;
         int attach;
-        PollEventCB call_back;
+        PollEventCB callBack;
     };
     unordered_map<int, Poll_Record::Ptr> _event_map;
 #endif //HAS_EPOLL
 
     //定时器相关
-    std::multimap<uint64_t, DelayTask::Ptr> _delay_task_map;
+    multimap<uint64_t, DelayTask::Ptr> _delay_task_map;
 };
 
 class EventPollerPool : public std::enable_shared_from_this<EventPollerPool>, public TaskExecutorGetterImp {
 public:
     using Ptr = std::shared_ptr<EventPollerPool>;
-    static const std::string kOnStarted;
-    ~EventPollerPool() = default;
+    ~EventPollerPool(){};
 
     /**
      * 获取单例
@@ -253,11 +246,6 @@ public:
     static void setPoolSize(size_t size = 0);
 
     /**
-     * 内部创建线程是否设置cpu亲和性,默认设置cpu亲和性
-     */
-    static void enableCpuAffinity(bool enable);
-
-    /**
      * 获取第一个实例
      * @return
      */
@@ -280,10 +268,10 @@ public:
     void preferCurrentThread(bool flag = true);
 
 private:
-    EventPollerPool();
+    EventPollerPool() ;
 
 private:
-    bool _prefer_current_thread = true;
+    bool _preferCurrentThread = true;
 };
 
 }  // namespace toolkit

+ 10 - 9
3rdparty/ZLToolKit/include/Poller/Pipe.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,25 +11,26 @@
 #ifndef Pipe_h
 #define Pipe_h
 
+#include <stdio.h>
 #include <functional>
 #include "PipeWrap.h"
 #include "EventPoller.h"
+using namespace std;
 
 namespace toolkit {
 
-class Pipe {
+class Pipe
+{
 public:
-    using onRead = std::function<void(int size, const char *buf)>;
-
-    Pipe(const onRead &cb = nullptr, const EventPoller::Ptr &poller = nullptr);
+    Pipe(const function<void(int size,const char *buf)> &onRead=nullptr, const EventPoller::Ptr &poller = nullptr);
     ~Pipe();
-
-    void send(const char *send, int size = 0);
-
+    void send(const char *send,int size=0);
 private:
     std::shared_ptr<PipeWrap> _pipe;
     EventPoller::Ptr _poller;
+
 };
 
+
 }  // namespace toolkit
-#endif /* Pipe_h */
+#endif /* Pipe_h */

+ 11 - 8
3rdparty/ZLToolKit/include/Poller/PipeWrap.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -19,15 +19,18 @@ public:
     ~PipeWrap();
     int write(const void *buf, int n);
     int read(void *buf, int n);
-    int readFD() const { return _pipe_fd[0]; }
-    int writeFD() const { return _pipe_fd[1]; }
-    void reOpen();
-
+    int readFD() const {
+        return _pipe_fd[0];
+    }
+    int writeFD() const {
+        return _pipe_fd[1];
+    }
 private:
+    int _pipe_fd[2] = { -1,-1 };
     void clearFD();
-
-private:
-    int _pipe_fd[2] = { -1, -1 };
+#if defined(_WIN32)
+    int _listenerFd = -1;
+#endif // defined(_WIN32)
 };
 
 } /* namespace toolkit */

+ 2 - 3
3rdparty/ZLToolKit/include/Poller/SelectWrap.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -25,8 +25,7 @@ public:
     bool isSet(int fd);
     void *_ptr;
 };
-
-int zl_select(int cnt, FdSet *read, FdSet *write, FdSet *err, struct timeval *tv);
+int zl_select(int cnt,FdSet *read,FdSet *write,FdSet *err,struct timeval *tv);
 
 } /* namespace toolkit */
 #endif /* SRC_POLLER_SELECTWRAP_H_ */

+ 10 - 5
3rdparty/ZLToolKit/include/Poller/Timer.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,26 +11,31 @@
 #ifndef Timer_h
 #define Timer_h
 
+#include <stdio.h>
 #include <functional>
 #include "EventPoller.h"
+using namespace std;
 
 namespace toolkit {
 
 class Timer {
 public:
-    using Ptr = std::shared_ptr<Timer>;
+    typedef std::shared_ptr<Timer> Ptr;
 
     /**
      * 构造定时器
      * @param second 定时器重复秒数
      * @param cb 定时器任务,返回true表示重复下次任务,否则不重复,如果任务中抛异常,则默认重复下次任务
      * @param poller EventPoller对象,可以为nullptr
+     * @param continueWhenException 定时回调中抛异常是否继续标记
      */
-    Timer(float second, const std::function<bool()> &cb, const EventPoller::Ptr &poller);
+    Timer(float second,
+          const function<bool()> &cb,
+          const EventPoller::Ptr &poller /*=nullptr*/,
+          bool continueWhenException = true );
     ~Timer();
-
 private:
-    std::weak_ptr<EventPoller::DelayTask> _tag;
+    weak_ptr<DelayTask> _tag;
     //定时器保持EventPoller的强引用
     EventPoller::Ptr _poller;
 };

+ 18 - 26
3rdparty/ZLToolKit/include/Thread/TaskExecutor.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,11 +11,13 @@
 #ifndef ZLTOOLKIT_TASKEXECUTOR_H
 #define ZLTOOLKIT_TASKEXECUTOR_H
 
-#include <mutex>
 #include <memory>
 #include <functional>
 #include "Util/List.h"
 #include "Util/util.h"
+#include "Util/onceToken.h"
+#include "Util/TimeTicker.h"
+using namespace std;
 
 namespace toolkit {
 
@@ -55,8 +57,8 @@ private:
             _sleep = slp;
         }
 
-        bool _sleep;
         uint64_t _time;
+        bool _sleep;
     };
 
 private:
@@ -65,7 +67,7 @@ private:
     uint64_t _last_wake_time;
     uint64_t _max_size;
     uint64_t _max_usec;
-    std::mutex _mtx;
+    mutex _mtx;
     List<TimeRecord> _time_list;
 };
 
@@ -83,7 +85,7 @@ template<class R, class... ArgTypes>
 class TaskCancelableImp<R(ArgTypes...)> : public TaskCancelable {
 public:
     using Ptr = std::shared_ptr<TaskCancelableImp>;
-    using func_type = std::function<R(ArgTypes...)>;
+    using func_type = function<R(ArgTypes...)>;
 
     ~TaskCancelableImp() = default;
 
@@ -101,14 +103,14 @@ public:
         return _strongTask && *_strongTask;
     }
 
-    void operator=(std::nullptr_t) {
+    void operator=(nullptr_t) {
         _strongTask = nullptr;
     }
 
     R operator()(ArgTypes ...args) const {
         auto strongTask = _weakTask.lock();
         if (strongTask && *strongTask) {
-            return (*strongTask)(std::forward<ArgTypes>(args)...);
+            return (*strongTask)(forward<ArgTypes>(args)...);
         }
         return defaultValue<R>();
     }
@@ -134,14 +136,14 @@ protected:
     std::shared_ptr<func_type> _strongTask;
 };
 
-using TaskIn = std::function<void()>;
+using TaskIn = function<void()>;
 using Task = TaskCancelableImp<void()>;
 
 class TaskExecutorInterface {
+
 public:
     TaskExecutorInterface() = default;
     virtual ~TaskExecutorInterface() = default;
-
     /**
      * 异步执行任务
      * @param task 任务
@@ -178,7 +180,7 @@ public:
 */
 class TaskExecutor : public ThreadLoadCounter, public TaskExecutorInterface {
 public:
-    using Ptr = std::shared_ptr<TaskExecutor>;
+    using Ptr = shared_ptr<TaskExecutor>;
 
     /**
      * 构造函数
@@ -191,7 +193,7 @@ public:
 
 class TaskExecutorGetter {
 public:
-    using Ptr = std::shared_ptr<TaskExecutorGetter>;
+    using Ptr = shared_ptr<TaskExecutorGetter>;
 
     virtual ~TaskExecutorGetter() = default;
 
@@ -200,11 +202,6 @@ public:
      * @return 任务执行器
      */
     virtual TaskExecutor::Ptr getExecutor() = 0;
-
-    /**
-     * 获取执行器个数
-     */
-    virtual size_t getExecutorSize() const = 0;
 };
 
 class TaskExecutorGetterImp : public TaskExecutorGetter {
@@ -222,31 +219,26 @@ public:
      * 获取所有线程的负载率
      * @return 所有线程的负载率
      */
-    std::vector<int> getExecutorLoad();
+    vector<int> getExecutorLoad();
 
     /**
      * 获取所有线程任务执行延时,单位毫秒
      * 通过此函数也可以大概知道线程负载情况
      * @return
      */
-    void getExecutorDelay(const std::function<void(const std::vector<int> &)> &callback);
+    void getExecutorDelay(const function<void(const vector<int> &)> &callback);
 
     /**
      * 遍历所有线程
      */
-    void for_each(const std::function<void(const TaskExecutor::Ptr &)> &cb);
-
-    /**
-     * 获取线程数
-     */
-    size_t getExecutorSize() const override;
+    void for_each(const function<void(const TaskExecutor::Ptr &)> &cb);
 
 protected:
-    size_t addPoller(const std::string &name, size_t size, int priority, bool register_thread, bool enable_cpu_affinity = true);
+    size_t addPoller(const string &name, size_t size, int priority, bool register_thread);
 
 protected:
     size_t _thread_pos = 0;
-    std::vector<TaskExecutor::Ptr> _threads;
+    vector<TaskExecutor::Ptr> _threads;
 };
 
 }//toolkit

+ 18 - 14
3rdparty/ZLToolKit/include/Thread/TaskQueue.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,9 +11,14 @@
 #ifndef TASKQUEUE_H_
 #define TASKQUEUE_H_
 
+#include <list>
+#include <deque>
+#include <atomic>
 #include <mutex>
+#include <functional>
 #include "Util/List.h"
 #include "semaphore.h"
+using namespace std;
 
 namespace toolkit {
 
@@ -25,46 +30,45 @@ public:
     template<typename C>
     void push_task(C &&task_func) {
         {
-            std::lock_guard<decltype(_mutex)> lock(_mutex);
+            lock_guard<decltype(_mutex)> lock(_mutex);
             _queue.emplace_back(std::forward<C>(task_func));
         }
         _sem.post();
     }
-
     template<typename C>
     void push_task_first(C &&task_func) {
         {
-            std::lock_guard<decltype(_mutex)> lock(_mutex);
+            lock_guard<decltype(_mutex)> lock(_mutex);
             _queue.emplace_front(std::forward<C>(task_func));
         }
         _sem.post();
     }
-
     //清空任务列队
     void push_exit(size_t n) {
         _sem.post(n);
     }
-
     //从列队获取一个任务,由执行线程执行
     bool get_task(T &tsk) {
         _sem.wait();
-        std::lock_guard<decltype(_mutex)> lock(_mutex);
-        if (_queue.empty()) {
+        lock_guard<decltype(_mutex)> lock(_mutex);
+        if (_queue.size() == 0) {
             return false;
         }
+        //改成右值引用后性能提升了1倍多!
         tsk = std::move(_queue.front());
         _queue.pop_front();
         return true;
     }
-
-    size_t size() const {
-        std::lock_guard<decltype(_mutex)> lock(_mutex);
+    size_t size() const{
+        lock_guard<decltype(_mutex)> lock(_mutex);
         return _queue.size();
     }
-
 private:
-    List <T> _queue;
-    mutable std::mutex _mutex;
+    //经过对比List,std::list,std::deque三种容器发现,
+    //在i5-6200U单线程环境下,执行1000万个任务时,分别耗时1.3,2.4,1.8秒左右
+    //所以此处我们替换成性能最好的List模板
+    List<T> _queue;
+    mutable mutex _mutex;
     semaphore _sem;
 };
 

+ 25 - 31
3rdparty/ZLToolKit/include/Thread/ThreadPool.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,15 +11,16 @@
 #ifndef THREADPOOL_H_
 #define THREADPOOL_H_
 
+#include <assert.h>
+#include <vector>
 #include "threadgroup.h"
 #include "TaskQueue.h"
 #include "TaskExecutor.h"
 #include "Util/util.h"
 #include "Util/logger.h"
-
 namespace toolkit {
 
-class ThreadPool : public TaskExecutor {
+class ThreadPool : public TaskExecutor{
 public:
     enum Priority {
         PRIORITY_LOWEST = 0,
@@ -29,30 +30,23 @@ public:
         PRIORITY_HIGHEST
     };
 
-    ThreadPool(int num = 1, Priority priority = PRIORITY_HIGHEST, bool auto_run = true, bool set_affinity = true,
-               const std::string &pool_name = "thread pool") {
-        _thread_num = num;
-        _on_setup = [pool_name, priority, set_affinity](int index) {
-            std::string name = pool_name + ' ' + std::to_string(index);
-            setPriority(priority);
-            setThreadName(name.data());
-            if (set_affinity) {
-                setThreadAffinity(index % std::thread::hardware_concurrency());
-            }
-        };
-        _logger = Logger::Instance().shared_from_this();
-        if (auto_run) {
+    //num:线程池线程个数
+    ThreadPool(int num = 1,
+               Priority priority = PRIORITY_HIGHEST,
+               bool autoRun = true) :
+            _thread_num(num), _priority(priority) {
+        if(autoRun){
             start();
         }
+        _logger = Logger::Instance().shared_from_this();
     }
-
     ~ThreadPool() {
         shutdown();
         wait();
     }
 
     //把任务打入线程池并异步执行
-    Task::Ptr async(TaskIn task, bool may_sync = true) override {
+    Task::Ptr async(TaskIn task,bool may_sync = true) override {
         if (may_sync && _thread_group.is_this_thread_in()) {
             task();
             return nullptr;
@@ -61,8 +55,7 @@ public:
         _queue.push_task(ret);
         return ret;
     }
-
-    Task::Ptr async_first(TaskIn task, bool may_sync = true) override {
+    Task::Ptr async_first(TaskIn task,bool may_sync = true) override{
         if (may_sync && _thread_group.is_this_thread_in()) {
             task();
             return nullptr;
@@ -73,11 +66,12 @@ public:
         return ret;
     }
 
-    size_t size() {
+    size_t size(){
         return _queue.size();
     }
 
-    static bool setPriority(Priority priority = PRIORITY_NORMAL, std::thread::native_handle_type threadId = 0) {
+    static bool setPriority(Priority priority = PRIORITY_NORMAL,
+            thread::native_handle_type threadId = 0) {
         // set priority
 #if defined(_WIN32)
         static int Priorities[] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST };
@@ -94,7 +88,8 @@ public:
         if (Max == -1) {
             return false;
         }
-        static int Priorities[] = {Min, Min + (Max - Min) / 4, Min + (Max - Min) / 2, Min + (Max - Min) * 3 / 4, Max};
+        static int Priorities[] = { Min, Min + (Max - Min) / 4, Min
+            + (Max - Min) / 2, Min + (Max - Min) * 3/ 4, Max };
 
         if (threadId == 0) {
             threadId = pthread_self();
@@ -111,13 +106,13 @@ public:
         }
         size_t total = _thread_num - _thread_group.size();
         for (size_t i = 0; i < total; ++i) {
-            _thread_group.create_thread([this, i]() {run(i);});
+            _thread_group.create_thread(bind(&ThreadPool::run, this));
         }
     }
 
 private:
-    void run(size_t index) {
-        _on_setup(index);
+    void run() {
+        ThreadPool::setPriority(_priority);
         Task::Ptr task;
         while (true) {
             startSleep();
@@ -130,7 +125,7 @@ private:
                 (*task)();
                 task = nullptr;
             } catch (std::exception &ex) {
-                ErrorL << "ThreadPool catch a exception: " << ex.what();
+                ErrorL << "ThreadPool执行任务捕获到异常:" << ex.what();
             }
         }
     }
@@ -142,13 +137,12 @@ private:
     void shutdown() {
         _queue.push_exit(_thread_num);
     }
-
 private:
     size_t _thread_num;
-    Logger::Ptr _logger;
-    thread_group _thread_group;
     TaskQueue<Task::Ptr> _queue;
-    std::function<void(int)> _on_setup;
+    thread_group _thread_group;
+    Priority _priority;
+    Logger::Ptr _logger;
 };
 
 } /* namespace toolkit */

+ 12 - 13
3rdparty/ZLToolKit/include/Thread/WorkThreadPool.h

@@ -1,45 +1,44 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
  * may be found in the AUTHORS file in the root of the source tree.
  */
-
+ 
 #ifndef UTIL_WORKTHREADPOOL_H_
 #define UTIL_WORKTHREADPOOL_H_
 
 #include <memory>
+#include "ThreadPool.h"
 #include "Poller/EventPoller.h"
+using namespace std;
 
 namespace toolkit {
 
-class WorkThreadPool : public std::enable_shared_from_this<WorkThreadPool>, public TaskExecutorGetterImp {
+class WorkThreadPool :
+        public std::enable_shared_from_this<WorkThreadPool> ,
+        public TaskExecutorGetterImp {
 public:
-    using Ptr = std::shared_ptr<WorkThreadPool>;
-
-    ~WorkThreadPool() override = default;
+    typedef std::shared_ptr<WorkThreadPool> Ptr;
+    ~WorkThreadPool(){};
 
     /**
      * 获取单例
+     * @return
      */
     static WorkThreadPool &Instance();
 
     /**
      * 设置EventPoller个数,在WorkThreadPool单例创建前有效
      * 在不调用此方法的情况下,默认创建thread::hardware_concurrency()个EventPoller实例
-     * @param size EventPoller个数,如果为0则为thread::hardware_concurrency()
+     * @param size  EventPoller个数,如果为0则为thread::hardware_concurrency()
      */
     static void setPoolSize(size_t size = 0);
 
     /**
-     * 内部创建线程是否设置cpu亲和性,默认设置cpu亲和性
-     */
-    static void enableCpuAffinity(bool enable);
-
-    /**
      * 获取第一个实例
      * @return
      */
@@ -53,7 +52,7 @@ public:
      */
     EventPoller::Ptr getPoller();
 
-protected:
+private:
     WorkThreadPool();
 };
 

+ 11 - 13
3rdparty/ZLToolKit/include/Thread/semaphore.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -14,14 +14,15 @@
 /*
  * 目前发现信号量在32位的系统上有问题,
  * 休眠的线程无法被正常唤醒,先禁用之
-#if defined(__linux__)
+ #if defined(__linux__)
 #include <semaphore.h>
 #define HAVE_SEM
 #endif //HAVE_SEM
 */
-
+#include <atomic>
 #include <mutex>
 #include <condition_variable>
+using namespace std;
 
 namespace toolkit {
 
@@ -34,48 +35,45 @@ public:
         _count = 0;
 #endif
     }
-
     ~semaphore() {
 #if defined(HAVE_SEM)
         sem_destroy(&_sem);
 #endif
     }
-
     void post(size_t n = 1) {
 #if defined(HAVE_SEM)
         while (n--) {
             sem_post(&_sem);
         }
 #else
-        std::unique_lock<std::recursive_mutex> lock(_mutex);
+        unique_lock<mutex> lock(_mutex);
         _count += n;
-        if (n == 1) {
+        if(n == 1){
             _condition.notify_one();
-        } else {
+        }else{
             _condition.notify_all();
         }
 #endif
-    }
 
+    }
     void wait() {
 #if defined(HAVE_SEM)
         sem_wait(&_sem);
 #else
-        std::unique_lock<std::recursive_mutex> lock(_mutex);
+        unique_lock<mutex> lock(_mutex);
         while (_count == 0) {
             _condition.wait(lock);
         }
         --_count;
 #endif
     }
-
 private:
 #if defined(HAVE_SEM)
     sem_t _sem;
 #else
     size_t _count;
-    std::recursive_mutex _mutex;
-    std::condition_variable_any _condition;
+    mutex _mutex;
+    condition_variable_any _condition;
 #endif
 };
 

+ 18 - 19
3rdparty/ZLToolKit/include/Thread/threadgroup.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,33 +11,35 @@
 #ifndef THREADGROUP_H_
 #define THREADGROUP_H_
 
-#include <stdexcept>
+#include <set>
+#include <mutex>
 #include <thread>
+#include <vector>
 #include <unordered_map>
+using namespace std;
 
 namespace toolkit {
 
 class thread_group {
 private:
-    thread_group(thread_group const &);
-    thread_group &operator=(thread_group const &);
-
+    thread_group(thread_group const&);
+    thread_group& operator=(thread_group const&);
 public:
-    thread_group() {}
-
+    thread_group() {
+    }
     ~thread_group() {
         _threads.clear();
     }
 
     bool is_this_thread_in() {
-        auto thread_id = std::this_thread::get_id();
-        if (_thread_id == thread_id) {
+        auto thread_id = this_thread::get_id();
+        if(_thread_id == thread_id){
             return true;
         }
         return _threads.find(thread_id) != _threads.end();
     }
 
-    bool is_thread_in(std::thread *thrd) {
+    bool is_thread_in(thread* thrd) {
         if (!thrd) {
             return false;
         }
@@ -46,23 +48,22 @@ public:
     }
 
     template<typename F>
-    std::thread *create_thread(F &&threadfunc) {
-        auto thread_new = std::make_shared<std::thread>(threadfunc);
+    thread* create_thread(F &&threadfunc) {
+        auto thread_new = std::make_shared<thread>(threadfunc);
         _thread_id = thread_new->get_id();
         _threads[_thread_id] = thread_new;
         return thread_new.get();
     }
 
-    void remove_thread(std::thread *thrd) {
+    void remove_thread(thread* thrd) {
         auto it = _threads.find(thrd->get_id());
         if (it != _threads.end()) {
             _threads.erase(it);
         }
     }
-
     void join_all() {
         if (is_this_thread_in()) {
-            throw std::runtime_error("Trying joining itself in thread_group");
+            throw runtime_error("thread_group: trying joining itself");
         }
         for (auto &it : _threads) {
             if (it.second->joinable()) {
@@ -71,14 +72,12 @@ public:
         }
         _threads.clear();
     }
-
     size_t size() {
         return _threads.size();
     }
-
 private:
-    std::thread::id _thread_id;
-    std::unordered_map<std::thread::id, std::shared_ptr<std::thread>> _threads;
+    unordered_map<thread::id, std::shared_ptr<thread> > _threads;
+    thread::id _thread_id;
 };
 
 } /* namespace toolkit */

+ 193 - 186
3rdparty/ZLToolKit/include/Util/CMD.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -16,197 +16,195 @@
 #include <string>
 #include <memory>
 #include <vector>
+#include <sstream>
 #include <iostream>
 #include <functional>
-#include "mini.h"
+#include "Util/mini.h"
+#include "Util/onceToken.h"
+using namespace std;
 
 namespace toolkit{
 
 class Option {
 public:
-    using OptionHandler = std::function<bool(const std::shared_ptr<std::ostream> &stream, const std::string &arg)>;
-
+    typedef function<bool(const std::shared_ptr<ostream> &stream, const string &arg)> OptionHandler;
     enum ArgType {
         ArgNone = 0,//no_argument,
         ArgRequired = 1,//required_argument,
         ArgOptional = 2,//optional_argument
     };
-
-    Option() = default;
-
-    Option(char short_opt, const char *long_opt, enum ArgType type, const char *default_value, bool must_exist,
-           const char *des, const OptionHandler &cb) {
-        _short_opt = short_opt;
-        _long_opt = long_opt;
-        _type = type;
-        if (type != ArgNone) {
-            if (default_value) {
-                _default_value = std::make_shared<std::string>(default_value);
+    Option(){}
+    Option(char shortOpt,
+           const char *longOpt,
+           enum ArgType argType,
+           const char *defaultValue,
+           bool mustExist,//该参数是否必须存在
+           const char *des,
+           const OptionHandler &cb) {
+        _shortOpt = shortOpt;
+        _longOpt = longOpt;
+        _argType = argType;
+        if(argType != ArgNone){
+            if(defaultValue){
+                _defaultValue = std::make_shared<string>(defaultValue);
             }
-            if (!_default_value && must_exist) {
-                _must_exist = true;
+            if(!_defaultValue && mustExist){
+                _mustExist = true;
             }
         }
         _des = des;
         _cb = cb;
     }
-
-    bool operator()(const std::shared_ptr<std::ostream> &stream, const std::string &arg) {
-        return _cb ? _cb(stream, arg) : true;
+    ~Option() {}
+    bool operator()(const std::shared_ptr<ostream> &stream, const string &arg){
+        return _cb ? _cb(stream,arg): true;
     }
-
 private:
     friend class OptionParser;
-    bool _must_exist = false;
-    char _short_opt;
-    enum ArgType _type;
-    std::string _des;
-    std::string _long_opt;
+    char _shortOpt;
+    string _longOpt;
+    std::shared_ptr<string> _defaultValue;
+    enum ArgType _argType;
+    string _des;
     OptionHandler _cb;
-    std::shared_ptr<std::string> _default_value;
+    bool _mustExist = false;
 };
 
 class OptionParser {
 public:
-    using OptionCompleted = std::function<void(const std::shared_ptr<std::ostream> &, mINI &)>;
-
-    OptionParser(const OptionCompleted &cb = nullptr, bool enable_empty_args = true) {
-        _on_completed = cb;
-        _enable_empty_args = enable_empty_args;
+    typedef function< void(const std::shared_ptr<ostream> &,mINI &)> OptionCompleted;
+    OptionParser(const OptionCompleted &cb = nullptr,bool enableEmptyArgs = true) {
+        _onCompleted = cb;
+        _enableEmptyArgs = enableEmptyArgs;
         _helper = Option('h', "help", Option::ArgNone, nullptr, false, "打印此信息",
-                         [this](const std::shared_ptr<std::ostream> &stream,const std::string &arg)->bool {
-             static const char *argsType[] = {"无参", "有参", "选参"};
-             static const char *mustExist[] = {"选填", "必填"};
-             static std::string defaultPrefix = "默认:";
-             static std::string defaultNull = "null";
-
-             std::stringstream printer;
-             size_t maxLen_longOpt = 0;
-             auto maxLen_default = defaultNull.size();
-
-             for (auto &pr : _map_options) {
-                 auto &opt = pr.second;
-                 if (opt._long_opt.size() > maxLen_longOpt) {
-                     maxLen_longOpt = opt._long_opt.size();
-                 }
-                 if (opt._default_value) {
-                     if (opt._default_value->size() > maxLen_default) {
-                         maxLen_default = opt._default_value->size();
-                     }
-                 }
-             }
-             for (auto &pr : _map_options) {
-                 auto &opt = pr.second;
-                 //打印短参和长参名
-                 if (opt._short_opt) {
-                     printer << "  -" << opt._short_opt << "  --" << opt._long_opt;
-                 } else {
-                     printer << "   " << " " << "  --" << opt._long_opt;
-                 }
-                 for (size_t i = 0; i < maxLen_longOpt - opt._long_opt.size(); ++i) {
-                     printer << " ";
-                 }
-                 //打印是否有参
-                 printer << "  " << argsType[opt._type];
-                 //打印默认参数
-                 std::string defaultValue = defaultNull;
-                 if (opt._default_value) {
-                     defaultValue = *opt._default_value;
-                 }
-                 printer << "  " << defaultPrefix << defaultValue;
-                 for (size_t i = 0; i < maxLen_default - defaultValue.size(); ++i) {
-                     printer << " ";
-                 }
-                 //打印是否必填参数
-                 printer << "  " << mustExist[opt._must_exist];
-                 //打印描述
-                 printer << "  " << opt._des << std::endl;
-             }
-             throw std::invalid_argument(printer.str());
-         });
+                         [this](const std::shared_ptr<ostream> &stream,const string &arg)->bool {
+            static const char *argsType[] = {"无参","有参","选参"};
+            static const char *mustExist[] = {"选填","必填"};
+            static string defaultPrefix = "默认:";
+            static string defaultNull = "null";
+
+            stringstream printer;
+            size_t maxLen_longOpt = 0;
+            auto maxLen_default = defaultNull.size();
+
+            for (auto &pr : _map_options) {
+                auto &opt = pr.second;
+                if(opt._longOpt.size() > maxLen_longOpt){
+                    maxLen_longOpt = opt._longOpt.size();
+                }
+                if(opt._defaultValue){
+                    if(opt._defaultValue->size() > maxLen_default){
+                        maxLen_default = opt._defaultValue->size();
+                    }
+                }
+            }
+            for (auto &pr : _map_options) {
+                auto &opt = pr.second;
+                //打印短参和长参名
+                if(opt._shortOpt){
+                    printer <<"  -" << opt._shortOpt <<"  --" << opt._longOpt;
+                }else{
+                    printer <<"   " << " " <<"  --" << opt._longOpt;
+                }
+                for (size_t i = 0; i < maxLen_longOpt - opt._longOpt.size(); ++i) {
+                    printer << " ";
+                }
+                //打印是否有参
+                printer << "  " << argsType[opt._argType];
+                //打印默认参数
+                string defaultValue = defaultNull;
+                if(opt._defaultValue){
+                    defaultValue = *opt._defaultValue;
+                }
+                printer << "  " << defaultPrefix << defaultValue;
+                for (size_t i = 0; i < maxLen_default - defaultValue.size(); ++i) {
+                    printer << " ";
+                }
+                //打印是否必填参数
+                printer << "  " << mustExist[opt._mustExist];
+                //打印描述
+                printer << "  " << opt._des << endl;
+            }
+            throw std::invalid_argument(printer.str());
+        });
         (*this) << _helper;
     }
+    ~OptionParser() {
+    }
 
-    OptionParser &operator<<(Option &&option) {
-        int index = 0xFF + (int) _map_options.size();
-        if (option._short_opt) {
-            _map_char_index.emplace(option._short_opt, index);
+    OptionParser &operator <<(Option &&option) {
+        int index = 0xFF + (int)_map_options.size();
+        if(option._shortOpt){
+            _map_charIndex.emplace(option._shortOpt,index);
         }
         _map_options.emplace(index, std::forward<Option>(option));
         return *this;
     }
-
-    OptionParser &operator<<(const Option &option) {
-        int index = 0xFF + (int) _map_options.size();
-        if (option._short_opt) {
-            _map_char_index.emplace(option._short_opt, index);
+    OptionParser &operator <<(const Option &option) {
+        int index = 0xFF + (int)_map_options.size();
+        if(option._shortOpt){
+            _map_charIndex.emplace(option._shortOpt,index);
         }
         _map_options.emplace(index, option);
         return *this;
     }
-
-    void delOption(const char *key) {
+    void delOption(const char *key){
         for (auto &pr : _map_options) {
-            if (pr.second._long_opt == key) {
-                if (pr.second._short_opt) {
-                    _map_char_index.erase(pr.second._short_opt);
+            if(pr.second._longOpt == key){
+                if(pr.second._shortOpt){
+                    _map_charIndex.erase(pr.second._shortOpt);
                 }
                 _map_options.erase(pr.first);
                 break;
             }
         }
     }
-
-    void operator ()(mINI &all_args, int argc, char *argv[], const std::shared_ptr<std::ostream> &stream);
-
+    void operator ()(mINI &allArg, int argc, char *argv[],const std::shared_ptr<ostream> &stream);
 private:
-    bool _enable_empty_args;
+    map<int,Option> _map_options;
+    map<char,int> _map_charIndex;
+    OptionCompleted _onCompleted;
     Option _helper;
-    std::map<char, int> _map_char_index;
-    std::map<int, Option> _map_options;
-    OptionCompleted _on_completed;
+    static mutex s_mtx_opt;
+    bool _enableEmptyArgs;
 };
 
-class CMD : public mINI {
+class CMD :public mINI{
 public:
-    virtual ~CMD() = default;
-
+    CMD(){};
+    virtual ~CMD(){};
     virtual const char *description() const {
         return "description";
     }
-
-    void operator()(int argc, char *argv[], const std::shared_ptr<std::ostream> &stream = nullptr) {
+    void operator ()(int argc, char *argv[],const std::shared_ptr<ostream> &stream = nullptr) {
         this->clear();
-        std::shared_ptr<std::ostream> coutPtr(&std::cout, [](std::ostream *) {});
-        (*_parser)(*this, argc, argv, stream ? stream : coutPtr);
+        std::shared_ptr<ostream> coutPtr(&cout,[](ostream *){});
+        (*_parser)(*this,argc, argv,stream? stream : coutPtr );
     }
 
-    bool hasKey(const char *key) {
+    bool hasKey(const char *key){
         return this->find(key) != this->end();
     }
 
-    std::vector<variant> splitedVal(const char *key, const char *delim = ":") {
-        std::vector<variant> ret;
+    vector<variant> splitedVal(const char *key,const char *delim= ":"){
+        vector<variant> ret;
         auto &val = (*this)[key];
-        split(val, delim, ret);
+        split(val,delim,ret);
         return ret;
     }
-
-    void delOption(const char *key) {
-        if (_parser) {
+    void delOption(const char *key){
+        if(_parser){
             _parser->delOption(key);
         }
     }
-
 protected:
     std::shared_ptr<OptionParser> _parser;
-
 private:
-    void split(const std::string &s, const char *delim, std::vector<variant> &ret) {
+    void split(const string& s, const char *delim,vector<variant> &ret){
         size_t last = 0;
         auto index = s.find(delim, last);
-        while (index != std::string::npos) {
-            if (index - last > 0) {
+        while (index != string::npos) {
+            if(index - last > 0){
                 ret.push_back(s.substr(last, index - last));
             }
             last = index + strlen(delim);
@@ -218,86 +216,84 @@ private:
     }
 };
 
-class CMDRegister {
+
+class CMDRegister
+{
 public:
+    CMDRegister() {};
+    ~CMDRegister(){};
     static CMDRegister &Instance();
-
-    void clear() {
-        std::lock_guard<std::recursive_mutex> lck(_mtx);
-        _cmd_map.clear();
+    void clear(){
+        lock_guard<recursive_mutex> lck(_mtxCMD);
+        _mapCMD.clear();
     }
-
-    void registCMD(const char *name, const std::shared_ptr<CMD> &cmd) {
-        std::lock_guard<std::recursive_mutex> lck(_mtx);
-        _cmd_map.emplace(name, cmd);
+    void registCMD(const char *name,const std::shared_ptr<CMD> &cmd){
+        lock_guard<recursive_mutex> lck(_mtxCMD);
+        _mapCMD.emplace(name,cmd);
     }
-
-    void unregistCMD(const char *name) {
-        std::lock_guard<std::recursive_mutex> lck(_mtx);
-        _cmd_map.erase(name);
+    void unregistCMD(const char *name){
+        lock_guard<recursive_mutex> lck(_mtxCMD);
+        _mapCMD.erase(name);
     }
-
-    std::shared_ptr<CMD> operator[](const char *name) {
-        std::lock_guard<std::recursive_mutex> lck(_mtx);
-        auto it = _cmd_map.find(name);
-        if (it == _cmd_map.end()) {
-            throw std::invalid_argument(std::string("CMD not existed: ") + name);
+    std::shared_ptr<CMD> operator[](const char *name){
+        lock_guard<recursive_mutex> lck(_mtxCMD);
+        auto it = _mapCMD.find(name);
+        if(it == _mapCMD.end()){
+            throw std::invalid_argument(string("命令不存在:") + name);
         }
         return it->second;
     }
 
-    void operator()(const char *name, int argc, char *argv[], const std::shared_ptr<std::ostream> &stream = nullptr) {
+    void operator()(const char *name,int argc,char *argv[],const std::shared_ptr<ostream> &stream = nullptr){
         auto cmd = (*this)[name];
-        if (!cmd) {
-            throw std::invalid_argument(std::string("CMD not existed: ") + name);
+        if(!cmd){
+            throw std::invalid_argument(string("命令不存在:") + name);
         }
-        (*cmd)(argc, argv, stream);
-    }
-
-    void printHelp(const std::shared_ptr<std::ostream> &streamTmp = nullptr) {
+        (*cmd)(argc,argv,stream);
+    };
+    void printHelp(const std::shared_ptr<ostream> &streamTmp = nullptr){
         auto stream = streamTmp;
-        if (!stream) {
-            stream.reset(&std::cout, [](std::ostream *) {});
+        if(!stream){
+            stream.reset(&cout,[](ostream *){});
         }
 
-        std::lock_guard<std::recursive_mutex> lck(_mtx);
+        lock_guard<recursive_mutex> lck(_mtxCMD);
         size_t maxLen = 0;
-        for (auto &pr : _cmd_map) {
-            if (pr.first.size() > maxLen) {
+        for (auto &pr : _mapCMD) {
+            if(pr.first.size() > maxLen){
                 maxLen = pr.first.size();
             }
         }
-        for (auto &pr : _cmd_map) {
+        for (auto &pr : _mapCMD) {
             (*stream) << "  " << pr.first;
             for (size_t i = 0; i < maxLen - pr.first.size(); ++i) {
                 (*stream) << " ";
             }
-            (*stream) << "  " << pr.second->description() << std::endl;
+            (*stream) << "  " << pr.second->description() << endl;
         }
-    }
-
-    void operator()(const std::string &line, const std::shared_ptr<std::ostream> &stream = nullptr) {
-        if (line.empty()) {
+    };
+    void operator()(const string &line,const std::shared_ptr<ostream> &stream = nullptr){
+        if(line.empty()){
             return;
         }
-        std::vector<char *> argv;
-        size_t argc = getArgs((char *) line.data(), argv);
+        vector<char *> argv;
+        size_t argc = getArgs((char *)line.data(), argv);
         if (argc == 0) {
             return;
         }
-        std::string cmd = argv[0];
-        std::lock_guard<std::recursive_mutex> lck(_mtx);
-        auto it = _cmd_map.find(cmd);
-        if (it == _cmd_map.end()) {
-            std::stringstream ss;
+        string cmd = argv[0];
+        lock_guard<recursive_mutex> lck(_mtxCMD);
+        auto it = _mapCMD.find(cmd);
+        if (it == _mapCMD.end()) {
+            stringstream ss;
             ss << "  未识别的命令\"" << cmd << "\",输入 \"help\" 获取帮助.";
             throw std::invalid_argument(ss.str());
         }
-        (*it->second)((int) argc, &argv[0], stream);
-    }
+        (*it->second)((int)argc,&argv[0],stream);
+    };
 
 private:
-    size_t getArgs(char *buf, std::vector<char *> &argv) {
+    size_t getArgs(char *buf, vector<char *> &argv) {
         size_t argc = 0;
         bool start = false;
         auto len = strlen(buf);
@@ -305,7 +301,7 @@ private:
             if (buf[i] != ' ' && buf[i] != '\t' && buf[i] != '\r' && buf[i] != '\n') {
                 if (!start) {
                     start = true;
-                    if (argv.size() < argc + 1) {
+                    if(argv.size() < argc + 1){
                         argv.resize(argc + 1);
                     }
                     argv[argc++] = buf + i;
@@ -317,36 +313,47 @@ private:
         }
         return argc;
     }
-
 private:
-    std::recursive_mutex _mtx;
-    std::map<std::string, std::shared_ptr<CMD> > _cmd_map;
+    map<string,std::shared_ptr<CMD> > _mapCMD;
+    recursive_mutex _mtxCMD;
+
 };
 
 //帮助命令(help),该命令默认已注册
-class CMD_help : public CMD {
+class CMD_help: public CMD {
 public:
-    CMD_help() {
-        _parser = std::make_shared<OptionParser>([](const std::shared_ptr<std::ostream> &stream, mINI &) {
+    CMD_help(){
+        _parser = std::make_shared<OptionParser>(nullptr);
+        (*_parser) << Option('c', "cmd", Option::ArgNone, nullptr ,false,"列出所有命令",
+                             [](const std::shared_ptr<ostream> &stream,const string &arg) {
             CMDRegister::Instance().printHelp(stream);
+            return true;
         });
     }
+    ~CMD_help() {}
 
     const char *description() const override {
         return "打印帮助信息";
     }
 };
 
-class ExitException : public std::exception {};
+class ExitException : public std::exception
+{
+public:
+    ExitException(){}
+    ~ExitException(){}
+
+};
 
 //退出程序命令(exit),该命令默认已注册
-class CMD_exit : public CMD {
+class CMD_exit: public CMD {
 public:
-    CMD_exit() {
-        _parser = std::make_shared<OptionParser>([](const std::shared_ptr<std::ostream> &, mINI &) {
+    CMD_exit(){
+        _parser = std::make_shared<OptionParser>([](const std::shared_ptr<ostream> &,mINI &){
             throw ExitException();
         });
     }
+    ~CMD_exit() {}
 
     const char *description() const override {
         return "退出shell";
@@ -357,20 +364,20 @@ public:
 #define CMD_quit CMD_exit
 
 //清空屏幕信息命令(clear),该命令默认已注册
-class CMD_clear : public CMD {
+class CMD_clear : public CMD
+{
 public:
-    CMD_clear() {
-        _parser = std::make_shared<OptionParser>([this](const std::shared_ptr<std::ostream> &stream, mINI &args) {
+    CMD_clear(){
+        _parser = std::make_shared<OptionParser>([this](const std::shared_ptr<ostream> &stream,mINI &args){
             clear(stream);
         });
     }
-
+    ~CMD_clear(){}
     const char *description() const {
         return "清空屏幕输出";
     }
-
 private:
-    void clear(const std::shared_ptr<std::ostream> &stream) {
+    void clear(const std::shared_ptr<ostream> &stream){
         (*stream) << "\x1b[2J\x1b[H";
         stream->flush();
     }

+ 16 - 44
3rdparty/ZLToolKit/include/Util/File.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,11 +11,12 @@
 #ifndef SRC_UTIL_FILE_H_
 #define SRC_UTIL_FILE_H_
 
-#include <cstdio>
-#include <cstdlib>
+#include <stdio.h>
+#include <stdlib.h>
 #include <string>
 #include "util.h"
 #include <functional>
+using namespace std;
 
 #if defined(__linux__)
 #include <limits.h>
@@ -52,42 +53,29 @@ struct dirent *readdir(DIR *);
 
 #endif // defined(_WIN32)
 
-#if defined(_WIN32) || defined(_WIN64)
-#define fseek64 _fseeki64
-#define ftell64 _ftelli64
-#else
-#define fseek64 fseek
-#define ftell64 ftell
-#endif
-
 namespace toolkit {
 
 class File {
 public:
     //创建路径
     static bool create_path(const char *file, unsigned int mod);
-
     //新建文件,目录文件夹自动生成
     static FILE *create_file(const char *file, const char *mode);
-
     //判断是否为目录
-    static bool is_dir(const char *path);
-
+    static bool is_dir(const char *path) ;
+    //判断是否为常规文件
+    static bool is_file(const char *path) ;
     //判断是否是特殊目录(. or ..)
     static bool is_special_dir(const char *path);
-
     //删除目录或文件
-    static int delete_file(const char *path);
-
-    //判断文件是否存在
-    static bool fileExist(const char *path);
+    static int delete_file(const char *path) ;
 
     /**
      * 加载文件内容至string
      * @param path 加载的文件路径
      * @return 文件内容
      */
-    static std::string loadFile(const char *path);
+    static string loadFile(const char *path);
 
     /**
      * 保存内容至文件
@@ -95,47 +83,31 @@ public:
      * @param path 保存的文件路径
      * @return 是否保存成功
      */
-    static bool saveFile(const std::string &data, const char *path);
+    static bool saveFile(const string &data,const char *path);
 
     /**
      * 获取父文件夹
      * @param path 路径
      * @return 文件夹
      */
-    static std::string parentDir(const std::string &path);
+    static string parentDir(const string &path);
 
     /**
      * 替换"../",获取绝对路径
      * @param path 相对路径,里面可能包含 "../"
-     * @param current_path 当前目录
-     * @param can_access_parent 能否访问父目录之外的目录
+     * @param currentPath 当前目录
+     * @param canAccessParent 能否访问父目录之外的目录
      * @return 替换"../"之后的路径
      */
-    static std::string absolutePath(const std::string &path, const std::string &current_path, bool can_access_parent = false);
+    static string absolutePath(const string &path, const string &currentPath,bool canAccessParent = false);
 
     /**
      * 遍历文件夹下的所有文件
      * @param path 文件夹路径
      * @param cb 回调对象 ,path为绝对路径,isDir为该路径是否为文件夹,返回true代表继续扫描,否则中断
-     * @param enter_subdirectory 是否进入子目录扫描
+     * @param enterSubdirectory 是否进入子目录扫描
      */
-    static void scanDir(const std::string &path, const std::function<bool(const std::string &path, bool isDir)> &cb, bool enter_subdirectory = false);
-
-    /**
-     * 获取文件大小
-     * @param fp 文件句柄
-     * @param remain_size true:获取文件剩余未读数据大小,false:获取文件总大小
-     */
-    static uint64_t fileSize(FILE *fp, bool remain_size = false);
-
-    /**
-     * 获取文件大小
-     * @param path 文件路径
-     * @return 文件大小
-     * @warning 调用者应确保文件存在
-     */
-    static uint64_t fileSize(const char *path);
-
+    static void scanDir(const string &path,const function<bool(const string &path,bool isDir)> &cb, bool enterSubdirectory = false);
 private:
     File();
     ~File();

+ 5 - 4
3rdparty/ZLToolKit/include/Util/List.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -13,6 +13,7 @@
 
 #include <list>
 #include <type_traits>
+using namespace std;
 
 namespace toolkit {
 
@@ -39,7 +40,7 @@ private:
 template<typename T>
 class List {
 public:
-    using NodeType = ListNode<T>;
+    typedef ListNode<T> NodeType;
     List(){}
     List(List &&that){
         swap(that);
@@ -182,10 +183,10 @@ private:
 #else
 
 template<typename T>
-class List : public std::list<T> {
+class List : public list<T> {
 public:
     template<typename ... ARGS>
-    List(ARGS &&...args) : std::list<T>(std::forward<ARGS>(args)...) {};
+    List(ARGS &&...args) : list<T>(std::forward<ARGS>(args)...) {};
 
     ~List() = default;
 

+ 2 - 1
3rdparty/ZLToolKit/include/Util/MD5.h

@@ -36,7 +36,8 @@ documentation and/or software.
 
 #include <string>
 #include <iostream>
-#include <cstdint>
+
+using namespace std;
 
 namespace toolkit {
 

+ 26 - 27
3rdparty/ZLToolKit/include/Util/NoticeCenter.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -17,37 +17,36 @@
 #include <exception>
 #include <functional>
 #include <unordered_map>
-#include <stdexcept>
+#include <thread>
 #include "function_traits.h"
+#include "onceToken.h"
+using namespace std;
 
 namespace toolkit {
 
 class EventDispatcher {
 public:
     friend class NoticeCenter;
-    using Ptr = std::shared_ptr<EventDispatcher>;
-
+    typedef std::shared_ptr<EventDispatcher> Ptr;
     ~EventDispatcher() = default;
 
 private:
-    using MapType = std::unordered_multimap<void *, std::shared_ptr<void> >;
-
+    typedef unordered_multimap<void *, std::shared_ptr<void> > MapType;
     EventDispatcher() = default;
 
     class InterruptException : public std::runtime_error {
     public:
         InterruptException() : std::runtime_error("InterruptException") {}
-
         ~InterruptException() {}
     };
 
     template<typename ...ArgsType>
     int emitEvent(ArgsType &&...args) {
-        using funType = std::function<void(decltype(std::forward<ArgsType>(args))...)>;
+        typedef function<void(decltype(std::forward<ArgsType>(args))...)> funType;
         decltype(_mapListener) copy;
         {
             //先拷贝(开销比较小),目的是防止在触发回调时还是上锁状态从而导致交叉互锁
-            std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+            lock_guard<recursive_mutex> lck(_mtxListener);
             copy = _mapListener;
         }
 
@@ -67,34 +66,34 @@ private:
 
     template<typename FUNC>
     void addListener(void *tag, FUNC &&func) {
-        using funType = typename function_traits<typename std::remove_reference<FUNC>::type>::stl_function_type;
+        typedef typename function_traits<typename std::remove_reference<FUNC>::type>::stl_function_type funType;
         std::shared_ptr<void> pListener(new funType(std::forward<FUNC>(func)), [](void *ptr) {
             funType *obj = (funType *) ptr;
             delete obj;
         });
-        std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+        lock_guard<recursive_mutex> lck(_mtxListener);
         _mapListener.emplace(tag, pListener);
     }
 
     void delListener(void *tag, bool &empty) {
-        std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+        lock_guard<recursive_mutex> lck(_mtxListener);
         _mapListener.erase(tag);
         empty = _mapListener.empty();
     }
 
 private:
-    std::recursive_mutex _mtxListener;
+    recursive_mutex _mtxListener;
     MapType _mapListener;
 };
 
 class NoticeCenter : public std::enable_shared_from_this<NoticeCenter> {
 public:
-    using Ptr = std::shared_ptr<NoticeCenter>;
-
+    typedef std::shared_ptr<NoticeCenter> Ptr;
+    ~NoticeCenter() {}
     static NoticeCenter &Instance();
 
     template<typename ...ArgsType>
-    int emitEvent(const std::string &strEvent, ArgsType &&...args) {
+    int emitEvent(const string &strEvent, ArgsType &&...args) {
         auto dispatcher = getDispatcher(strEvent);
         if (!dispatcher) {
             //该事件无人监听
@@ -104,11 +103,11 @@ public:
     }
 
     template<typename FUNC>
-    void addListener(void *tag, const std::string &event, FUNC &&func) {
+    void addListener(void *tag, const string &event, FUNC &&func) {
         getDispatcher(event, true)->addListener(tag, std::forward<FUNC>(func));
     }
 
-    void delListener(void *tag, const std::string &event) {
+    void delListener(void *tag, const string &event) {
         auto dispatcher = getDispatcher(event);
         if (!dispatcher) {
             //不存在该事件
@@ -123,7 +122,7 @@ public:
 
     //这个方法性能比较差
     void delListener(void *tag) {
-        std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+        lock_guard<recursive_mutex> lck(_mtxListener);
         bool empty;
         for (auto it = _mapListener.begin(); it != _mapListener.end();) {
             it->second->delListener(tag, empty);
@@ -136,13 +135,12 @@ public:
     }
 
     void clearAll() {
-        std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+        lock_guard<recursive_mutex> lck(_mtxListener);
         _mapListener.clear();
     }
-
 private:
-    EventDispatcher::Ptr getDispatcher(const std::string &event, bool create = false) {
-        std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+    EventDispatcher::Ptr getDispatcher(const string &event, bool create = false) {
+        lock_guard<recursive_mutex> lck(_mtxListener);
         auto it = _mapListener.find(event);
         if (it != _mapListener.end()) {
             return it->second;
@@ -156,8 +154,8 @@ private:
         return nullptr;
     }
 
-    void delDispatcher(const std::string &event, const EventDispatcher::Ptr &dispatcher) {
-        std::lock_guard<std::recursive_mutex> lck(_mtxListener);
+    void delDispatcher(const string &event, const EventDispatcher::Ptr &dispatcher) {
+        lock_guard<recursive_mutex> lck(_mtxListener);
         auto it = _mapListener.find(event);
         if (it != _mapListener.end() && dispatcher == it->second) {
             //两者相同则删除
@@ -165,9 +163,10 @@ private:
         }
     }
 
+    NoticeCenter() {}
 private:
-    std::recursive_mutex _mtxListener;
-    std::unordered_map<std::string, EventDispatcher::Ptr> _mapListener;
+    recursive_mutex _mtxListener;
+    unordered_map<string, EventDispatcher::Ptr> _mapListener;
 };
 
 } /* namespace toolkit */

+ 70 - 83
3rdparty/ZLToolKit/include/Util/ResourcePool.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,27 +11,28 @@
 #ifndef UTIL_RECYCLEPOOL_H_
 #define UTIL_RECYCLEPOOL_H_
 
-#include "List.h"
-#include <atomic>
+#include <mutex>
 #include <deque>
-#include <functional>
 #include <memory>
-#include <mutex>
+#include <atomic>
+#include <functional>
 #include <unordered_set>
+#include "Util/List.h"
+using namespace std;
 
 namespace toolkit {
 
-#if (defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ >= 4 && __GNUC_MINOR__ >= 9))) || defined(__clang__)             \
-    || !defined(__GNUC__)
+#if (defined(__GNUC__) && ( __GNUC__ >= 5 || (__GNUC__ >= 4 && __GNUC_MINOR__ >= 9))) || defined(__clang__) || !defined(__GNUC__)
 #define SUPPORT_DYNAMIC_TEMPLATE
 #endif
 
-template <typename C>
+
+template<typename C>
 class ResourcePool_l;
-template <typename C>
+template<typename C>
 class ResourcePool;
 
-template <typename C>
+template<typename C>
 class shared_ptr_imp : public std::shared_ptr<C> {
 public:
     shared_ptr_imp() {}
@@ -42,153 +43,139 @@ public:
      * @param weakPool 管理本指针的循环池
      * @param quit 对接是否放弃循环使用
      */
-    shared_ptr_imp(
-        C *ptr, const std::weak_ptr<ResourcePool_l<C>> &weakPool, std::shared_ptr<std::atomic_bool> quit,
-        const std::function<void(C *)> &on_recycle);
+    shared_ptr_imp(C *ptr,
+                   const std::weak_ptr<ResourcePool_l<C> > &weakPool,
+                   std::shared_ptr<atomic_bool> quit,
+                   const function<void(C *)> &on_recycle);
 
     /**
      * 放弃或恢复回到循环池继续使用
      * @param flag
      */
-    void quit(bool flag = true) {
-        if (_quit) {
+    void quit(bool flag = true){
+        if(_quit){
             *_quit = flag;
         }
     }
-
 private:
-    std::shared_ptr<std::atomic_bool> _quit;
+    std::shared_ptr<atomic_bool> _quit;
 };
 
-template <typename C>
-class ResourcePool_l : public std::enable_shared_from_this<ResourcePool_l<C>> {
+template<typename C>
+class ResourcePool_l: public enable_shared_from_this<ResourcePool_l<C> > {
 public:
-    using ValuePtr = shared_ptr_imp<C>;
+    typedef shared_ptr_imp<C> ValuePtr;
     friend class shared_ptr_imp<C>;
     friend class ResourcePool<C>;
 
     ResourcePool_l() {
-        _alloc = []() -> C * { return new C(); };
+        _allotter = []()->C* {
+            return new C();
+        };
     }
 
 #if defined(SUPPORT_DYNAMIC_TEMPLATE)
-    template <typename... ArgTypes>
+    template<typename ...ArgTypes>
     ResourcePool_l(ArgTypes &&...args) {
-        _alloc = [args...]() -> C * { return new C(args...); };
+        _allotter = [args...]()->C* {
+            return new C(args...);
+        };
     }
-#endif // defined(SUPPORT_DYNAMIC_TEMPLATE)
+#endif //defined(SUPPORT_DYNAMIC_TEMPLATE)
 
-    ~ResourcePool_l() {
-        for (auto ptr : _objs) {
+    ~ResourcePool_l(){
+        _objs.for_each([](C *ptr){
             delete ptr;
-        }
+        });
     }
 
     void setSize(size_t size) {
-        _pool_size = size;
-        _objs.reserve(size);
-    }
-
-    ValuePtr obtain(const std::function<void(C *)> &on_recycle = nullptr) {
-        return ValuePtr(getPtr(), _weak_self, std::make_shared<std::atomic_bool>(false), on_recycle);
-    }
-
-    std::shared_ptr<C> obtain2() {
-        auto weak_self = _weak_self;
-        return std::shared_ptr<C>(getPtr(), [weak_self](C *ptr) {
-            auto strongPool = weak_self.lock();
-            if (strongPool) {
-                //放入循环池
-                strongPool->recycle(ptr);
-            } else {
-                delete ptr;
-            }
-        });
+        _poolsize = size;
     }
 
-private:
-    void recycle(C *obj) {
+    ValuePtr obtain(const function<void(C *)> &on_recycle = nullptr) {
+        C *ptr;
         auto is_busy = _busy.test_and_set();
         if (!is_busy) {
             //获取到锁
-            if (_objs.size() >= _pool_size) {
-                delete obj;
+            if (_objs.size() == 0) {
+                ptr = _allotter();
             } else {
-                _objs.emplace_back(obj);
+                ptr = _objs.front();
+                _objs.pop_front();
             }
             _busy.clear();
         } else {
             //未获取到锁
-            delete obj;
+            ptr = _allotter();
         }
+        return ValuePtr(ptr, _weak_self, std::make_shared<atomic_bool>(false), on_recycle);
     }
 
-    C *getPtr() {
-        C *ptr;
+private:
+    void recycle(C *obj) {
         auto is_busy = _busy.test_and_set();
         if (!is_busy) {
             //获取到锁
-            if (_objs.size() == 0) {
-                ptr = _alloc();
+            if (_objs.size() >= _poolsize) {
+                delete obj;
             } else {
-                ptr = _objs.back();
-                _objs.pop_back();
+                _objs.emplace_back(obj);
             }
             _busy.clear();
         } else {
             //未获取到锁
-            ptr = _alloc();
+            delete obj;
         }
-        return ptr;
     }
 
-    void setup() { _weak_self = this->shared_from_this(); }
+    void setup(){
+        _weak_self = this->shared_from_this();
+    }
 
 private:
-    size_t _pool_size = 8;
-    std::vector<C *> _objs;
-    std::function<C *(void)> _alloc;
-    std::atomic_flag _busy { false };
-    std::weak_ptr<ResourcePool_l> _weak_self;
+    size_t _poolsize = 8;
+    List<C*> _objs;
+    function<C*(void)> _allotter;
+    atomic_flag _busy{false};
+    weak_ptr<ResourcePool_l > _weak_self;
 };
 
 /**
  * 循环池,注意,循环池里面的对象不能继承enable_shared_from_this!
  * @tparam C
  */
-template <typename C>
+template<typename C>
 class ResourcePool {
 public:
-    using ValuePtr = shared_ptr_imp<C>;
+    typedef shared_ptr_imp<C> ValuePtr;
     ResourcePool() {
         pool.reset(new ResourcePool_l<C>());
         pool->setup();
     }
 #if defined(SUPPORT_DYNAMIC_TEMPLATE)
-    template <typename... ArgTypes>
+    template<typename ...ArgTypes>
     ResourcePool(ArgTypes &&...args) {
-        pool = std::make_shared<ResourcePool_l<C>>(std::forward<ArgTypes>(args)...);
+        pool = std::make_shared<ResourcePool_l<C> >(std::forward<ArgTypes>(args)...);
         pool->setup();
     }
-#endif // defined(SUPPORT_DYNAMIC_TEMPLATE)
-    void setSize(size_t size) { pool->setSize(size); }
-
-    //获取一个对象,性能差些,但是功能丰富些
-    ValuePtr obtain(const std::function<void(C *)> &on_recycle = nullptr) { return pool->obtain(on_recycle); }
-
-    //获取一个对象,性能好些
-    std::shared_ptr<C> obtain2() { return pool->obtain2(); }
-
+#endif //defined(SUPPORT_DYNAMIC_TEMPLATE)
+    void setSize(size_t size) {
+        pool->setSize(size);
+    }
+    ValuePtr obtain(const function<void(C *)> &on_recycle = nullptr) {
+        return pool->obtain(on_recycle);
+    }
 private:
-    std::shared_ptr<ResourcePool_l<C>> pool;
+    std::shared_ptr<ResourcePool_l<C> > pool;
 };
 
 template<typename C>
 shared_ptr_imp<C>::shared_ptr_imp(C *ptr,
                                   const std::weak_ptr<ResourcePool_l<C> > &weakPool,
-                                  std::shared_ptr<std::atomic_bool> quit,
-                                  const std::function<void(C *)> &on_recycle) :
-    std::shared_ptr<C>(ptr, [weakPool, quit, on_recycle](C *ptr) {
+                                  std::shared_ptr<atomic_bool> quit,
+                                  const function<void(C *)> &on_recycle) :
+        shared_ptr<C>(ptr, [weakPool, quit, on_recycle](C *ptr) {
             if (on_recycle) {
                 on_recycle(ptr);
             }

+ 146 - 201
3rdparty/ZLToolKit/include/Util/RingBuffer.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,7 +11,6 @@
 #ifndef UTIL_RINGBUFFER_H_
 #define UTIL_RINGBUFFER_H_
 
-#include <assert.h>
 #include <atomic>
 #include <memory>
 #include <mutex>
@@ -20,102 +19,105 @@
 #include <functional>
 #include "List.h"
 #include "Poller/EventPoller.h"
+using namespace std;
 
-// GOP缓存最大长度下限值
+//GOP缓存最大长度下限值
 #define RING_MIN_SIZE 32
-#define LOCK_GUARD(mtx) std::lock_guard<decltype(mtx)> lck(mtx)
+#define LOCK_GUARD(mtx) lock_guard<decltype(mtx)> lck(mtx)
 
 namespace toolkit {
 
-using ReaderInfo = std::shared_ptr<void>;
-
-template <typename T>
+template<typename T>
 class RingDelegate {
 public:
-    using Ptr = std::shared_ptr<RingDelegate>;
-    RingDelegate() = default;
-    virtual ~RingDelegate() = default;
+    typedef std::shared_ptr<RingDelegate> Ptr;
+    RingDelegate() {}
+    virtual ~RingDelegate() {}
     virtual void onWrite(T in, bool is_key = true) = 0;
 };
 
-template <typename T>
+template<typename T>
 class _RingStorage;
 
-template <typename T>
+template<typename T>
 class _RingReaderDispatcher;
 
 /**
- * 环形缓存读取器
- * 该对象的事件触发都会在绑定的poller线程中执行
- * 所以把锁去掉了
- * 对该对象的一切操作都应该在poller线程中执行
- */
-template <typename T>
+* 环形缓存读取器
+* 该对象的事件触发都会在绑定的poller线程中执行
+* 所以把锁去掉了
+* 对该对象的一切操作都应该在poller线程中执行
+* @tparam T
+*/
+template<typename T>
 class _RingReader {
 public:
-    using Ptr = std::shared_ptr<_RingReader>;
+    typedef std::shared_ptr<_RingReader> Ptr;
     friend class _RingReaderDispatcher<T>;
 
-    _RingReader(std::shared_ptr<_RingStorage<T>> storage) { _storage = std::move(storage); }
+    _RingReader(const std::shared_ptr<_RingStorage<T> > &storage, bool use_cache) {
+        _storage = storage;
+        _use_cache = use_cache;
+    }
 
-    ~_RingReader() = default;
+    ~_RingReader() {}
 
-    void setReadCB(std::function<void(const T &)> cb) {
+    void setReadCB(const function<void(const T &)> &cb) {
         if (!cb) {
             _read_cb = [](const T &) {};
         } else {
-            _read_cb = std::move(cb);
+            _read_cb = cb;
             flushGop();
         }
     }
 
-    void setDetachCB(std::function<void()> cb) {
-        _detach_cb = cb ? std::move(cb) : []() {};
-    }
-
-    void setGetInfoCB(std::function<ReaderInfo()> cb) {
-        _get_info = cb ? std::move(cb) : []() { return ReaderInfo(); };
+    void setDetachCB(const function<void()> &cb) {
+        if (!cb) {
+            _detach_cb = []() {};
+        } else {
+            _detach_cb = cb;
+        }
     }
 
 private:
-    void onRead(const T &data, bool /*is_key*/) { _read_cb(data); }
+    void onRead(const T &data, bool is_key) {
+        _read_cb(data);
+    }
 
-    void onDetach() const { _detach_cb(); }
+    void onDetach() const {
+        _detach_cb();
+    }
 
     void flushGop() {
-        if (!_storage) {
+        if (!_use_cache) {
             return;
         }
-        _storage->getCache().for_each([this](const List<std::pair<bool, T>> &lst) {
-            lst.for_each([this](const std::pair<bool, T> &pr) { onRead(pr.second, pr.first); });
+        _storage->getCache().for_each([&](const pair<bool, T> &pr) {
+            onRead(pr.second, pr.first);
         });
     }
 
-    ReaderInfo getInfo() { return _get_info(); }
-
 private:
-    std::shared_ptr<_RingStorage<T>> _storage;
-    std::function<void(void)> _detach_cb = []() {};
-    std::function<void(const T &)> _read_cb = [](const T &) {};
-    std::function<ReaderInfo()> _get_info = []() { return ReaderInfo(); };
+    bool _use_cache;
+    shared_ptr<_RingStorage<T> > _storage;
+    function<void(void)> _detach_cb = []() {};
+    function<void(const T &)> _read_cb = [](const T &) {};
 };
 
-template <typename T>
+template<typename T>
 class _RingStorage {
 public:
-    using Ptr = std::shared_ptr<_RingStorage>;
-    using GopType = List<List<std::pair<bool, T>>>;
-    _RingStorage(size_t max_size, size_t max_gop_size) {
-        // gop缓存个数不能小于32
-        if (max_size < RING_MIN_SIZE) {
+    typedef std::shared_ptr<_RingStorage> Ptr;
+
+    _RingStorage(int max_size) {
+        //gop缓存个数不能小于32
+        if(max_size < RING_MIN_SIZE){
             max_size = RING_MIN_SIZE;
         }
         _max_size = max_size;
-        _max_gop_size = max_gop_size;
-        clearCache();
     }
 
-    ~_RingStorage() = default;
+    ~_RingStorage() {}
 
     /**
      * 写入环形缓存数据
@@ -123,35 +125,24 @@ public:
      * @param is_key 是否为关键帧
      * @return 是否触发重置环形缓存大小
      */
-    void write(T in, bool is_key = true) {
+     void write(T in, bool is_key = true) {
         if (is_key) {
+            //遇到I帧,那么移除老数据
+            _size = 0;
             _have_idr = true;
-            _started = true;
-            if (!_data_cache.back().empty()) {
-                //当前gop列队还没收到任意缓存
-                _data_cache.emplace_back();
-            }
-            if (_data_cache.size() > _max_gop_size) {
-                // GOP个数超过限制,那么移除最早的GOP
-                popFrontGop();
-            }
+            _data_cache.clear();
         }
 
-        if (!_have_idr && _started) {
+        if (!_have_idr) {
             //缓存中没有关键帧,那么gop缓存无效
             return;
         }
-        _data_cache.back().emplace_back(std::make_pair(is_key, std::move(in)));
+        _data_cache.emplace_back(std::make_pair(is_key, std::move(in)));
         if (++_size > _max_size) {
-            // GOP缓存溢出
-            while (_data_cache.size() > 1) {
-                //先尝试清除老的GOP缓存
-                popFrontGop();
-            }
-            if (_size > _max_size) {
-                //还是大于最大缓冲限制,那么清空所有GOP
-                clearCache();
-            }
+            //GOP缓存溢出,清空关老数据
+            _size = 0;
+            _have_idr = false;
+            _data_cache.clear();
         }
     }
 
@@ -159,58 +150,43 @@ public:
         Ptr ret(new _RingStorage());
         ret->_size = _size;
         ret->_have_idr = _have_idr;
-        ret->_started = _started;
         ret->_max_size = _max_size;
-        ret->_max_gop_size = _max_gop_size;
         ret->_data_cache = _data_cache;
         return ret;
     }
 
-    const GopType &getCache() const { return _data_cache; }
+    const List<pair<bool, T> > &getCache() const {
+        return _data_cache;
+    }
 
-    void clearCache() {
+    void clearCache(){
         _size = 0;
-        _have_idr = false;
         _data_cache.clear();
-        _data_cache.emplace_back();
     }
 
 private:
     _RingStorage() = default;
 
-    void popFrontGop() {
-        if (!_data_cache.empty()) {
-            _size -= _data_cache.front().size();
-            _data_cache.pop_front();
-            if (_data_cache.empty()) {
-                _data_cache.emplace_back();
-            }
-        }
-    }
-
 private:
-    bool _started = false;
-    bool _have_idr;
-    size_t _size;
-    size_t _max_size;
-    size_t _max_gop_size;
-    GopType _data_cache;
+    bool _have_idr = false;
+    int _size = 0;
+    int _max_size;
+    List<pair<bool, T> > _data_cache;
 };
 
-template <typename T>
+template<typename T>
 class RingBuffer;
 
 /**
- * 环形缓存事件派发器,只能一个poller线程操作它
- * @tparam T
- */
-template <typename T>
-class _RingReaderDispatcher : public std::enable_shared_from_this<_RingReaderDispatcher<T>> {
+* 环形缓存事件派发器,只能一个poller线程操作它
+* @tparam T
+*/
+template<typename T>
+class _RingReaderDispatcher : public enable_shared_from_this<_RingReaderDispatcher<T> > {
 public:
-    using Ptr = std::shared_ptr<_RingReaderDispatcher>;
-    using RingReader = _RingReader<T>;
-    using RingStorage = _RingStorage<T>;
-    using onChangeInfoCB = std::function<ReaderInfo(ReaderInfo &&info)>;
+    typedef std::shared_ptr<_RingReaderDispatcher> Ptr;
+    typedef _RingReader<T> RingReader;
+    typedef _RingStorage<T> RingStorage;
 
     friend class RingBuffer<T>;
 
@@ -226,12 +202,10 @@ public:
     }
 
 private:
-    _RingReaderDispatcher(
-        const typename RingStorage::Ptr &storage, std::function<void(int, bool)> onSizeChanged) {
-        _reader_size = 0;
+    _RingReaderDispatcher(const typename RingStorage::Ptr &storage, const function<void(int, bool)> &onSizeChanged) {
         _storage = storage;
-        _on_size_changed = std::move(onSizeChanged);
-        assert(_on_size_changed);
+        _reader_size = 0;
+        _on_size_changed = onSizeChanged;
     }
 
     void write(T in, bool is_key = true) {
@@ -251,77 +225,60 @@ private:
 
     std::shared_ptr<RingReader> attach(const EventPoller::Ptr &poller, bool use_cache) {
         if (!poller->isCurrentThread()) {
-            throw std::runtime_error("You can attach RingBuffer only in it's poller thread");
+            throw std::runtime_error("必须在绑定的poller线程中执行attach操作");
         }
 
-        std::weak_ptr<_RingReaderDispatcher> weak_self = this->shared_from_this();
-        auto on_dealloc = [weak_self, poller](RingReader *ptr) {
-            poller->async([weak_self, ptr]() {
-                auto strong_self = weak_self.lock();
-                if (strong_self && strong_self->_reader_map.erase(ptr)) {
-                    --strong_self->_reader_size;
-                    strong_self->onSizeChanged(false);
+        weak_ptr<_RingReaderDispatcher> weakSelf = this->shared_from_this();
+        auto on_dealloc = [weakSelf, poller](RingReader *ptr) {
+            poller->async([weakSelf, ptr]() {
+                auto strongSelf = weakSelf.lock();
+                if (strongSelf && strongSelf->_reader_map.erase(ptr)) {
+                    --strongSelf->_reader_size;
+                    strongSelf->onSizeChanged(false);
                 }
                 delete ptr;
             });
         };
 
-        std::shared_ptr<RingReader> reader(new RingReader(use_cache ? _storage : nullptr), on_dealloc);
-        _reader_map[reader.get()] = reader;
+        std::shared_ptr<RingReader> reader(new RingReader(_storage, use_cache), on_dealloc);
+        _reader_map[reader.get()] = std::move(reader);
         ++_reader_size;
         onSizeChanged(true);
         return reader;
     }
 
-    void onSizeChanged(bool add_flag) { _on_size_changed(_reader_size, add_flag); }
-
-    void clearCache() {
-        if (_reader_size == 0) {
-            _storage->clearCache();
-        }
+    void onSizeChanged(bool add_flag) {
+        _on_size_changed(_reader_size, add_flag);
     }
 
-    std::list<ReaderInfo> getInfoList(const onChangeInfoCB &on_change) {
-        std::list<ReaderInfo> ret;
-        for (auto &pr : _reader_map) {
-            auto reader = pr.second.lock();
-            if (!reader) {
-                continue;
-            }
-            auto info = reader->getInfo();
-            if (!info) {
-                continue;
-            }
-            ret.emplace_back(on_change(std::move(info)));
+    void clearCache(){
+        if(_reader_size  == 0){
+            _storage->clearCache();
         }
-        return ret;
     }
 
 private:
-    std::atomic_int _reader_size;
-    std::function<void(int, bool)> _on_size_changed;
+    atomic_int _reader_size;
+    function<void(int, bool)> _on_size_changed;
     typename RingStorage::Ptr _storage;
-    std::unordered_map<void *, std::weak_ptr<RingReader>> _reader_map;
+    unordered_map<void *, std::weak_ptr<RingReader> > _reader_map;
 };
 
-template <typename T>
-class RingBuffer : public std::enable_shared_from_this<RingBuffer<T>> {
+template<typename T>
+class RingBuffer : public enable_shared_from_this<RingBuffer<T> > {
 public:
-    using Ptr = std::shared_ptr<RingBuffer>;
-    using RingReader = _RingReader<T>;
-    using RingStorage = _RingStorage<T>;
-    using RingReaderDispatcher = _RingReaderDispatcher<T>;
-    using onReaderChanged = std::function<void(int size)>;
-    using onGetInfoCB = std::function<void(std::list<ReaderInfo> &info_list)>;
-
-    RingBuffer(size_t max_size = 1024, onReaderChanged cb = nullptr, size_t max_gop_size = 1) {
-        _storage = std::make_shared<RingStorage>(max_size, max_gop_size);
-        _on_reader_changed = cb ? std::move(cb) : [](int size) {};
-        //先触发无人观看
-        _on_reader_changed(0);
+    typedef std::shared_ptr<RingBuffer> Ptr;
+    typedef _RingReader<T> RingReader;
+    typedef _RingStorage<T> RingStorage;
+    typedef _RingReaderDispatcher<T> RingReaderDispatcher;
+    typedef function<void(int size)> onReaderChanged;
+
+    RingBuffer(int max_size = 1024, const onReaderChanged &cb = nullptr) {
+        _on_reader_changed = cb;
+        _storage = std::make_shared<RingStorage>(max_size);
     }
 
-    ~RingBuffer() = default;
+    ~RingBuffer() {}
 
     void write(T in, bool is_key = true) {
         if (_delegate) {
@@ -333,12 +290,16 @@ public:
         for (auto &pr : _dispatcher_map) {
             auto &second = pr.second;
             //切换线程后触发onRead事件
-            pr.first->async([second, in, is_key]() { second->write(std::move(const_cast<T &>(in)), is_key); }, false);
+            pr.first->async([second, in, is_key]() {
+                second->write(std::move(const_cast<T &>(in)), is_key);
+            }, false);
         }
         _storage->write(std::move(in), is_key);
     }
 
-    void setDelegate(const typename RingDelegate<T>::Ptr &delegate) { _delegate = delegate; }
+    void setDelegate(const typename RingDelegate<T>::Ptr &delegate) {
+        _delegate = delegate;
+    }
 
     std::shared_ptr<RingReader> attach(const EventPoller::Ptr &poller, bool use_cache = true) {
         typename RingReaderDispatcher::Ptr dispatcher;
@@ -346,13 +307,20 @@ public:
             LOCK_GUARD(_mtx_map);
             auto &ref = _dispatcher_map[poller];
             if (!ref) {
-                std::weak_ptr<RingBuffer> weak_self = this->shared_from_this();
-                auto onSizeChanged = [weak_self, poller](int size, bool add_flag) {
-                    if (auto strong_self = weak_self.lock()) {
-                        strong_self->onSizeChanged(poller, size, add_flag);
+                weak_ptr<RingBuffer> weakSelf = this->shared_from_this();
+                auto onSizeChanged = [weakSelf, poller](int size, bool add_flag) {
+                    auto strongSelf = weakSelf.lock();
+                    if (!strongSelf) {
+                        return;
                     }
+                    strongSelf->onSizeChanged(poller, size, add_flag);
+                };
+
+                auto onDealloc = [poller](RingReaderDispatcher *ptr) {
+                    poller->async([ptr]() {
+                        delete ptr;
+                    });
                 };
-                auto onDealloc = [poller](RingReaderDispatcher *ptr) { poller->async([ptr]() { delete ptr; }); };
                 ref.reset(new RingReaderDispatcher(_storage->clone(), std::move(onSizeChanged)), std::move(onDealloc));
             }
             dispatcher = ref;
@@ -361,47 +329,19 @@ public:
         return dispatcher->attach(poller, use_cache);
     }
 
-    int readerCount() { return _total_count; }
+    int readerCount() {
+        return _total_count;
+    }
 
-    void clearCache() {
+    void clearCache(){
         LOCK_GUARD(_mtx_map);
         _storage->clearCache();
         for (auto &pr : _dispatcher_map) {
             auto &second = pr.second;
             //切换线程后清空缓存
-            pr.first->async([second]() { second->clearCache(); }, false);
-        }
-    }
-
-    void getInfoList(const onGetInfoCB &cb, const typename RingReaderDispatcher::onChangeInfoCB &on_change = nullptr) {
-        if (!cb) {
-            return;
-        }
-        if (!on_change) {
-            const_cast<typename RingReaderDispatcher::onChangeInfoCB &>(on_change) = [](ReaderInfo &&info) { return std::move(info); };
-        }
-
-        LOCK_GUARD(_mtx_map);
-
-        auto info_vec = std::make_shared<std::vector<std::list<ReaderInfo>>>();
-        // 1、最少确保一个元素
-        info_vec->resize(_dispatcher_map.empty() ? 1 : _dispatcher_map.size());
-        std::shared_ptr<void> on_finished(nullptr, [cb, info_vec](void *) mutable {
-            // 2、防止这里为空
-            auto &lst = *info_vec->begin();
-            for (auto &item : *info_vec) {
-                if (&lst != &item) {
-                    lst.insert(lst.end(), item.begin(), item.end());
-                }
-            }
-            cb(lst);
-        });
-
-        auto i = 0U;
-        for (auto &pr : _dispatcher_map) {
-            auto &second = pr.second;
-            pr.first->async([second, info_vec, on_finished, i, on_change]() { (*info_vec)[i] = second->getInfoList(on_change); });
-            ++i;
+            pr.first->async([second]() {
+                second->clearCache();
+            }, false);
         }
     }
 
@@ -417,21 +357,26 @@ private:
         } else {
             --_total_count;
         }
-        _on_reader_changed(_total_count);
+
+        if (_on_reader_changed) {
+            _on_reader_changed(_total_count);
+        }
     }
 
 private:
     struct HashOfPtr {
-        std::size_t operator()(const EventPoller::Ptr &key) const { return (std::size_t)key.get(); }
+        std::size_t operator()(const EventPoller::Ptr &key) const {
+            return (std::size_t) key.get();
+        }
     };
 
 private:
-    std::mutex _mtx_map;
-    std::atomic_int _total_count { 0 };
+    mutex _mtx_map;
+    atomic_int _total_count {0};
     typename RingStorage::Ptr _storage;
     typename RingDelegate<T>::Ptr _delegate;
     onReaderChanged _on_reader_changed;
-    std::unordered_map<EventPoller::Ptr, typename RingReaderDispatcher::Ptr, HashOfPtr> _dispatcher_map;
+    unordered_map<EventPoller::Ptr, typename RingReaderDispatcher::Ptr, HashOfPtr> _dispatcher_map;
 };
 
 } /* namespace toolkit */

+ 0 - 3
3rdparty/ZLToolKit/include/Util/SHA1.h

@@ -21,8 +21,6 @@
 #include <iostream>
 #include <string>
 
-namespace toolkit {
-
 class SHA1 final
 {
 public:
@@ -44,4 +42,3 @@ private:
     uint64_t transforms;
 };
 
-}//namespace toolkit

+ 27 - 32
3rdparty/ZLToolKit/include/Util/SSLBox.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -18,7 +18,8 @@
 #include "List.h"
 #include "util.h"
 #include "Network/Buffer.h"
-#include "ResourcePool.h"
+#include "Util/ResourcePool.h"
+using namespace std;
 
 typedef struct x509_st X509;
 typedef struct evp_pkey_st EVP_PKEY;
@@ -31,7 +32,6 @@ namespace toolkit {
 class SSL_Initor {
 public:
     friend class SSL_Box;
-
     static SSL_Initor &Instance();
 
     /**
@@ -44,8 +44,7 @@ public:
      * @param is_file 参数pem_or_p12是否为文件路径
      * @param is_default 是否为默认证书
      */
-    bool loadCertificate(const std::string &pem_or_p12, bool server_mode = true, const std::string &password = "",
-                         bool is_file = true, bool is_default = true);
+    bool loadCertificate(const string &pem_or_p12, bool server_mode = true, const string &password = "", bool is_file = true, bool is_default = true);
 
     /**
      * 是否忽略无效的证书
@@ -63,8 +62,7 @@ public:
      * @param is_file 是否为文件路径
      * @return 是否加载成功
      */
-    bool trustCertificate(const std::string &pem_p12_cer, bool server_mode = false, const std::string &password = "",
-                          bool is_file = true);
+    bool trustCertificate(const string &pem_p12_cer, bool server_mode = false, const string &password = "", bool is_file = true);
 
     /**
      * 信任某证书
@@ -72,7 +70,7 @@ public:
      * @param server_mode 是否为服务模式
      * @return 是否加载成功
      */
-    bool trustCertificate(X509 *cer, bool server_mode = false);
+    bool trustCertificate(X509 *cer,bool server_mode = false);
 
 private:
     SSL_Initor();
@@ -81,7 +79,7 @@ private:
     /**
      * 创建SSL对象
      */
-    std::shared_ptr<SSL> makeSSL(bool server_mode);
+    shared_ptr<SSL> makeSSL(bool server_mode);
 
     /**
      * 设置ssl context
@@ -90,7 +88,7 @@ private:
      * @param server_mode ssl context
      * @param is_default 是否为默认证书
      */
-    bool setContext(const std::string &vhost, const std::shared_ptr<SSL_CTX> &ctx, bool server_mode, bool is_default = true);
+    bool setContext(const string &vhost, const std::shared_ptr<SSL_CTX> &ctx, bool server_mode, bool is_default = true);
 
     /**
      * 设置SSL_CTX的默认配置
@@ -104,16 +102,14 @@ private:
      * @param server_mode 是否为服务器模式
      * @return SSL_CTX对象
      */
-    std::shared_ptr<SSL_CTX> getSSLCtx(const std::string &vhost, bool server_mode);
-
-    std::shared_ptr<SSL_CTX> getSSLCtx_l(const std::string &vhost, bool server_mode);
-
-    std::shared_ptr<SSL_CTX> getSSLCtxWildcards(const std::string &vhost, bool server_mode);
+    std::shared_ptr<SSL_CTX> getSSLCtx(const string &vhost, bool server_mode);
+    std::shared_ptr<SSL_CTX> getSSLCtx_l(const string &vhost, bool server_mode);
+    std::shared_ptr<SSL_CTX> getSSLCtxWildcards(const string &vhost, bool server_mode);
 
     /**
      * 获取默认的虚拟主机
      */
-    std::string defaultVhost(bool server_mode);
+    string defaultVhost(bool server_mode);
 
     /**
      * 完成vhost name 匹配的回调函数
@@ -121,17 +117,18 @@ private:
     static int findCertificate(SSL *ssl, int *ad, void *arg);
 
 private:
+
     struct less_nocase {
-        bool operator()(const std::string &x, const std::string &y) const {
+        bool operator()(const string &x, const string &y) const {
             return strcasecmp(x.data(), y.data()) < 0;
         }
     };
 
 private:
-    std::string _default_vhost[2];
     std::shared_ptr<SSL_CTX> _ctx_empty[2];
-    std::map<std::string, std::shared_ptr<SSL_CTX>, less_nocase> _ctxs[2];
-    std::map<std::string, std::shared_ptr<SSL_CTX>, less_nocase> _ctxs_wildcards[2];
+    map<string, std::shared_ptr<SSL_CTX>, less_nocase> _ctxs[2];
+    map<string, std::shared_ptr<SSL_CTX>, less_nocase > _ctxs_wildcards[2];
+    string _default_vhost[2];
 };
 
 ////////////////////////////////////////////////////////////////////////////////////
@@ -139,7 +136,6 @@ private:
 class SSL_Box {
 public:
     SSL_Box(bool server_mode = true, bool enable = true, int buff_size = 32 * 1024);
-
     ~SSL_Box();
 
     /**
@@ -152,19 +148,19 @@ public:
      * 需要加密明文调用此函数
      * @param buffer 需要加密的明文数据
      */
-    void onSend(Buffer::Ptr buffer);
+    void onSend(const Buffer::Ptr &buffer);
 
     /**
      * 设置解密后获取明文的回调
      * @param cb 回调对象
      */
-    void setOnDecData(const std::function<void(const Buffer::Ptr &)> &cb);
+    void setOnDecData(const function<void(const Buffer::Ptr &)> &cb);
 
     /**
      * 设置加密后获取密文的回调
      * @param cb 回调对象
      */
-    void setOnEncData(const std::function<void(const Buffer::Ptr &)> &cb);
+    void setOnEncData(const function<void(const Buffer::Ptr &)> &cb);
 
     /**
      * 终结ssl
@@ -185,21 +181,20 @@ public:
 
 private:
     void flushWriteBio();
-
     void flushReadBio();
 
 private:
     bool _server_mode;
     bool _send_handshake;
-    bool _is_flush = false;
-    int _buff_size;
+    shared_ptr<SSL> _ssl;
     BIO *_read_bio;
     BIO *_write_bio;
-    std::shared_ptr<SSL> _ssl;
-    List <Buffer::Ptr> _buffer_send;
-    ResourcePool <BufferRaw> _buffer_pool;
-    std::function<void(const Buffer::Ptr &)> _on_dec;
-    std::function<void(const Buffer::Ptr &)> _on_enc;
+    function<void(const Buffer::Ptr &)> _on_dec;
+    function<void(const Buffer::Ptr &)> _on_enc;
+    List<Buffer::Ptr> _buffer_send;
+    ResourcePool<BufferRaw> _buffer_pool;
+    int _buff_size;
+    bool _is_flush = false;
 };
 
 } /* namespace toolkit */

+ 17 - 12
3rdparty/ZLToolKit/include/Util/SSLUtil.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -14,6 +14,7 @@
 #include <memory>
 #include <string>
 #include <vector>
+using namespace std;
 
 typedef struct x509_st X509;
 typedef struct evp_pkey_st EVP_PKEY;
@@ -21,7 +22,7 @@ typedef struct ssl_ctx_st SSL_CTX;
 typedef struct ssl_st SSL;
 typedef struct bio_st BIO;
 
-namespace toolkit {
+namespace toolkit{
 /**
  * ssl证书后缀一般分为以下几种
  * pem:这个是base64的字符编码串,可能存在公钥、私钥或者两者都存在
@@ -39,7 +40,7 @@ public:
      * @param isFile 是否为文件
      * @return 公钥证书列表
      */
-    static std::vector<std::shared_ptr<X509> > loadPublicKey(const std::string &file_path_or_data, const std::string &passwd = "", bool isFile = true);
+    static vector<shared_ptr<X509> > loadPublicKey(const string &file_path_or_data,const string &passwd = "",bool isFile = true);
 
     /**
      * 加载私钥证书,支持pem,p12后缀
@@ -48,7 +49,7 @@ public:
      * @param isFile 是否为文件
      * @return 私钥证书
      */
-    static std::shared_ptr<EVP_PKEY> loadPrivateKey(const std::string &file_path_or_data, const std::string &passwd = "", bool isFile = true);
+    static shared_ptr<EVP_PKEY> loadPrivateKey(const string &file_path_or_data,const string &passwd = "",bool isFile = true);
 
     /**
      * 创建SSL_CTX对象
@@ -57,13 +58,15 @@ public:
      * @param serverMode 是否为服务器模式或客户端模式
      * @return SSL_CTX对象
      */
-    static std::shared_ptr<SSL_CTX> makeSSLContext(const std::vector<std::shared_ptr<X509> > &cers, const std::shared_ptr<EVP_PKEY> &key, bool serverMode = true, bool checkKey = false);
+    static shared_ptr<SSL_CTX> makeSSLContext(const vector<shared_ptr<X509> > &cers, const shared_ptr<EVP_PKEY> &key, bool serverMode = true);
 
     /**
      * 创建ssl对象
      * @param ctx SSL_CTX对象
+     * @return
      */
-    static std::shared_ptr<SSL> makeSSL(SSL_CTX *ctx);
+    static shared_ptr<SSL> makeSSL(SSL_CTX *ctx);
+
 
     /**
      * specifies that the default locations from which CA certificates are loaded should be used.
@@ -74,22 +77,24 @@ public:
      *  Alternatively the SSL_CERT_FILE environment variable can be defined to override this location.
      * 信任/usr/local/ssl/certs/目录下的所有证书/usr/local/ssl/cert.pem的证书
      * 环境变量SSL_CERT_FILE将替换/usr/local/ssl/cert.pem的路径
+     * @param ctx
      */
     static bool loadDefaultCAs(SSL_CTX *ctx);
 
     /**
      * 信任某公钥
+     * @param cer
      */
-    static bool trustCertificate(SSL_CTX *ctx, X509 *cer);
+    static bool trustCertificate(SSL_CTX *ctx , X509 *cer);
 
 
     /**
      * 验证证书合法性
      * @param cer 待验证的证书
-     * @param ... 信任的CA根证书,X509类型,以nullptr结尾
+     * @param ... 信任的CA根证书,X509类型,以NULL结尾
      * @return 是否合法
      */
-    static bool verifyX509(X509 *cer, ...);
+    static bool verifyX509(X509 *cer,...);
 
     /**
      * 使用公钥加解密数据
@@ -98,7 +103,7 @@ public:
      * @param enc_or_dec true:加密,false:解密
      * @return 加密或解密后的数据
      */
-    static std::string cryptWithRsaPublicKey(X509 *cer, const std::string &in_str, bool enc_or_dec);
+    static string cryptWithRsaPublicKey(X509 *cer , const string &in_str,bool enc_or_dec);
 
     /**
      * 使用私钥加解密数据
@@ -107,14 +112,14 @@ public:
      * @param enc_or_dec true:加密,false:解密
      * @return 加密或解密后的数据
      */
-    static std::string cryptWithRsaPrivateKey(EVP_PKEY *private_key, const std::string &in_str, bool enc_or_dec);
+    static string cryptWithRsaPrivateKey(EVP_PKEY *private_key, const string &in_str, bool enc_or_dec);
 
     /**
      * 获取证书域名
      * @param cer 证书公钥
      * @return 证书域名
      */
-    static std::string getServerName(X509 *cer);
+    static string getServerName(X509 *cer);
 };
 
 }//namespace toolkit

+ 66 - 73
3rdparty/ZLToolKit/include/Util/SqlConnection.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,9 +11,9 @@
 #ifndef SQL_SQLCONNECTION_H_
 #define SQL_SQLCONNECTION_H_
 
-#include <cstdio>
-#include <cstdarg>
-#include <cstring>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
 #include <string>
 #include <vector>
 #include <list>
@@ -21,37 +21,36 @@
 #include <sstream>
 #include <iostream>
 #include <stdexcept>
-#include "logger.h"
-#include "util.h"
-#include <mysql.h>
-
+#include "Util/logger.h"
+#include "Util/util.h"
 #if defined(_WIN32)
+#include <mysql.h>
 #pragma  comment (lib,"libmysql") 
-#endif
+#else
+#include <mysql/mysql.h>
+#endif // defined(_WIN32)
+using namespace std;
 
 namespace toolkit {
 
 /**
  * 数据库异常类
  */
-class SqlException : public std::exception {
+class SqlException : public exception {
 public:
-    SqlException(const std::string &sql, const std::string &err) {
+    SqlException(const string &sql,const string &err){
         _sql = sql;
         _err = err;
     }
-
-    virtual const char *what() const noexcept {
+    virtual const char* what() const noexcept {
         return _err.data();
     }
-
-    const std::string &getSql() const {
+    const string &getSql() const{
         return _sql;
     }
-
 private:
-    std::string _sql;
-    std::string _err;
+    string _sql;
+    string _err;
 };
 
 /**
@@ -68,27 +67,27 @@ public:
      * @param password 用户密码
      * @param character 字符集
      */
-    SqlConnection(const std::string &url, unsigned short port,
-                  const std::string &dbname, const std::string &username,
-                  const std::string &password, const std::string &character = "utf8mb4") {
+    SqlConnection(const string &url, unsigned short port,
+                  const string &dbname, const string &username,
+                  const string &password, const string &character = "utf8mb4") {
         mysql_init(&_sql);
         unsigned int timeout = 3;
         mysql_options(&_sql, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);
         if (!mysql_real_connect(&_sql, url.data(), username.data(),
-                                password.data(), dbname.data(), port, nullptr, 0)) {
+                                password.data(), dbname.data(), port, NULL, 0)) {
             mysql_close(&_sql);
-            throw SqlException("mysql_real_connect", mysql_error(&_sql));
+            throw SqlException("mysql_real_connect",mysql_error(&_sql));
         }
         //兼容bool与my_bool
         uint32_t reconnect = 0x01010101;
         mysql_options(&_sql, MYSQL_OPT_RECONNECT, &reconnect);
         mysql_set_character_set(&_sql, character.data());
     }
-
-    ~SqlConnection() {
+    ~SqlConnection(){
         mysql_close(&_sql);
     }
 
+
     /**
      * 以printf样式执行sql,无数据返回
      * @param rowId insert时的插入rowid
@@ -96,14 +95,14 @@ public:
      * @param arg 可变参数列表
      * @return 影响行数
      */
-    template<typename Fmt, typename ...Args>
-    int64_t query(int64_t &rowId, Fmt &&fmt, Args &&...arg) {
+    template<typename Fmt,typename ...Args>
+    int64_t query(int64_t &rowId, Fmt &&fmt, Args && ...arg) {
         check();
         auto tmp = queryString(std::forward<Fmt>(fmt), std::forward<Args>(arg)...);
         if (doQuery(tmp)) {
-            throw SqlException(tmp, mysql_error(&_sql));
+            throw SqlException(tmp,mysql_error(&_sql));
         }
-        rowId = mysql_insert_id(&_sql);
+        rowId=mysql_insert_id(&_sql);
         return mysql_affected_rows(&_sql);
     }
 
@@ -115,19 +114,17 @@ public:
      * @param arg 可变参数列表
      * @return 影响行数
      */
-    template<typename Fmt, typename ...Args>
-    int64_t query(int64_t &rowId, std::vector<std::vector<std::string> > &ret, Fmt &&fmt, Args &&...arg) {
-        return queryList(rowId, ret, std::forward<Fmt>(fmt), std::forward<Args>(arg)...);
+    template<typename Fmt,typename ...Args>
+    int64_t query(int64_t &rowId,vector<vector<string> > &ret, Fmt &&fmt, Args && ...arg){
+        return queryList(rowId,ret,std::forward<Fmt>(fmt),std::forward<Args>(arg)...);
     }
-
-    template<typename Fmt, typename... Args>
-    int64_t query(int64_t &rowId, std::vector<std::list<std::string>> &ret, Fmt &&fmt, Args &&...arg) {
-        return queryList(rowId, ret, std::forward<Fmt>(fmt), std::forward<Args>(arg)...);
+    template<typename Fmt,typename ...Args>
+    int64_t query(int64_t &rowId,vector<list<string> > &ret, Fmt &&fmt, Args && ...arg){
+        return queryList(rowId,ret,std::forward<Fmt>(fmt),std::forward<Args>(arg)...);
     }
-
-    template<typename Fmt, typename ...Args>
-    int64_t query(int64_t &rowId, std::vector<std::deque<std::string> > &ret, Fmt &&fmt, Args &&...arg) {
-        return queryList(rowId, ret, std::forward<Fmt>(fmt), std::forward<Args>(arg)...);
+    template<typename Fmt,typename ...Args>
+    int64_t query(int64_t &rowId,vector<deque<string> > &ret, Fmt &&fmt, Args && ...arg){
+        return queryList(rowId,ret,std::forward<Fmt>(fmt),std::forward<Args>(arg)...);
     }
 
     /**
@@ -138,47 +135,48 @@ public:
      * @param arg 可变参数列表
      * @return 影响行数
      */
-    template<typename Map, typename Fmt, typename ...Args>
-    int64_t query(int64_t &rowId, std::vector<Map> &ret, Fmt &&fmt, Args &&...arg) {
+    template<typename Map,typename Fmt,typename ...Args>
+    int64_t query(int64_t &rowId,vector<Map> &ret, Fmt &&fmt, Args && ...arg) {
         check();
         auto tmp = queryString(std::forward<Fmt>(fmt), std::forward<Args>(arg)...);
         if (doQuery(tmp)) {
-            throw SqlException(tmp, mysql_error(&_sql));
+            throw SqlException(tmp,mysql_error(&_sql));
         }
         ret.clear();
         MYSQL_RES *res = mysql_store_result(&_sql);
         if (!res) {
-            rowId = mysql_insert_id(&_sql);
+            rowId=mysql_insert_id(&_sql);
             return mysql_affected_rows(&_sql);
         }
         MYSQL_ROW row;
         unsigned int column = mysql_num_fields(res);
         MYSQL_FIELD *fields = mysql_fetch_fields(res);
-        while ((row = mysql_fetch_row(res)) != nullptr) {
+        while ((row = mysql_fetch_row(res)) != NULL) {
             ret.emplace_back();
             auto &back = ret.back();
             for (unsigned int i = 0; i < column; i++) {
-                back[std::string(fields[i].name, fields[i].name_length)] = (row[i] ? row[i] : "");
+                back[string(fields[i].name,fields[i].name_length)] = (row[i] ? row[i] : "");
             }
         }
         mysql_free_result(res);
-        rowId = mysql_insert_id(&_sql);
+        rowId=mysql_insert_id(&_sql);
         return mysql_affected_rows(&_sql);
     }
 
-    std::string escape(const std::string &str) {
+    string escape(const string &str) {
         char *out = new char[str.length() * 2 + 1];
         mysql_real_escape_string(&_sql, out, str.c_str(), str.size());
-        std::string ret(out);
-        delete[] out;
+        string ret(out);
+        delete [] out;
         return ret;
     }
 
     template<typename ...Args>
-    static std::string queryString(const char *fmt, Args &&...arg) {
-        char *ptr_out = nullptr;
-        if (asprintf(&ptr_out, fmt, arg...) > 0 && ptr_out) {
-            std::string ret(ptr_out);
+    static string queryString(const char *fmt, Args && ...arg) {
+        char *ptr_out = NULL;
+        asprintf(&ptr_out, fmt, arg...);
+        if (ptr_out) {
+            string ret(ptr_out);
             free(ptr_out);
             return ret;
         }
@@ -186,35 +184,32 @@ public:
     }
 
     template<typename ...Args>
-    static std::string queryString(const std::string &fmt, Args &&...args) {
-        return queryString(fmt.data(), std::forward<Args>(args)...);
+    static string queryString(const string &fmt, Args && ...args) {
+        return queryString(fmt.data(),std::forward<Args>(args)...);
     }
-
     static const char *queryString(const char *fmt) {
         return fmt;
     }
-
-    static const std::string &queryString(const std::string &fmt) {
+    static const string &queryString(const string &fmt) {
         return fmt;
     }
-
 private:
-    template<typename List, typename Fmt, typename... Args>
-    int64_t queryList(int64_t &rowId, std::vector<List> &ret, Fmt &&fmt, Args &&...arg) {
+    template<typename List,typename Fmt,typename ...Args>
+    int64_t queryList(int64_t &rowId,vector<List> &ret, Fmt &&fmt, Args && ...arg) {
         check();
         auto tmp = queryString(std::forward<Fmt>(fmt), std::forward<Args>(arg)...);
         if (doQuery(tmp)) {
-            throw SqlException(tmp, mysql_error(&_sql));
+            throw SqlException(tmp,mysql_error(&_sql));
         }
         ret.clear();
         MYSQL_RES *res = mysql_store_result(&_sql);
         if (!res) {
-            rowId = mysql_insert_id(&_sql);
+            rowId=mysql_insert_id(&_sql);
             return mysql_affected_rows(&_sql);
         }
         MYSQL_ROW row;
         unsigned int column = mysql_num_fields(res);
-        while ((row = mysql_fetch_row(res)) != nullptr) {
+        while ((row = mysql_fetch_row(res)) != NULL) {
             ret.emplace_back();
             auto &back = ret.back();
             for (unsigned int i = 0; i < column; i++) {
@@ -222,24 +217,22 @@ private:
             }
         }
         mysql_free_result(res);
-        rowId = mysql_insert_id(&_sql);
+        rowId=mysql_insert_id(&_sql);
         return mysql_affected_rows(&_sql);
     }
 
     inline void check() {
         if (mysql_ping(&_sql) != 0) {
-            throw SqlException("mysql_ping", "Mysql connection ping failed");
+            throw SqlException("mysql_ping","MYSQL连接异常!");
         }
     }
 
-    int doQuery(const std::string &sql) {
-        return mysql_query(&_sql, sql.data());
+    int doQuery(const string &sql){
+        return mysql_query(&_sql,sql.data());
     }
-
-    int doQuery(const char *sql) {
-        return mysql_query(&_sql, sql);
+    int doQuery(const char *sql){
+        return mysql_query(&_sql,sql);
     }
-
 private:
     MYSQL _sql;
 };

+ 55 - 63
3rdparty/ZLToolKit/include/Util/SqlPool.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -16,19 +16,20 @@
 #include <memory>
 #include <sstream>
 #include <functional>
-#include "logger.h"
 #include "Poller/Timer.h"
+#include "logger.h"
 #include "SqlConnection.h"
 #include "Thread/WorkThreadPool.h"
-#include "ResourcePool.h"
+#include "Util/ResourcePool.h"
+using namespace std;
 
 namespace toolkit {
 
 class SqlPool : public std::enable_shared_from_this<SqlPool> {
 public:
-    using Ptr = std::shared_ptr<SqlPool>;
-    using PoolType = ResourcePool<SqlConnection>;
-    using SqlRetType = std::vector<std::vector<std::string> >;
+    typedef std::shared_ptr<SqlPool> Ptr;
+    typedef ResourcePool<SqlConnection> PoolType;
+    typedef vector<vector<string> > SqlRetType;
 
     static SqlPool &Instance();
 
@@ -55,7 +56,7 @@ public:
      * @param arg
      */
     template<typename ...Args>
-    void Init(Args &&...arg) {
+    void Init(Args && ...arg) {
         _pool.reset(new PoolType(std::forward<Args>(arg)...));
         _pool->obtain();
     }
@@ -87,7 +88,7 @@ public:
             //捕获执行异常
             mysql = _pool->obtain();
             return mysql->query(std::forward<Args>(arg)...);
-        } catch (std::exception &e) {
+        } catch (exception &e) {
             mysql.quit();
             throw;
         }
@@ -99,15 +100,15 @@ public:
      * @param str
      * @return
      */
-    std::string escape(const std::string &str) {
+    string escape(const string &str) {
         checkInited();
-        return _pool->obtain()->escape(const_cast<std::string &>(str));
+        return _pool->obtain()->escape(const_cast<string &>(str));
     }
 
 private:
-    SqlPool() {
+    SqlPool()  {
         _threadPool = WorkThreadPool::Instance().getExecutor();
-        _timer = std::make_shared<Timer>(30, [this]() {
+        _timer = std::make_shared<Timer>(30,[this](){
             flushError();
             return true;
         }, nullptr);
@@ -118,20 +119,20 @@ private:
      * @param sql sql语句
      * @param tryCnt 重试次数
      */
-    void asyncQuery_l(const std::string &sql, int tryCnt = 3) {
-        auto lam = [this, sql, tryCnt]() {
+    void asyncQuery_l(const string &sql,int tryCnt = 3) {
+        auto lam = [this,sql,tryCnt]() {
             int64_t rowID;
             auto cnt = tryCnt - 1;
             try {
-                syncQuery(rowID, sql);
-            } catch (std::exception &ex) {
-                if (cnt > 0) {
+                syncQuery(rowID,sql);
+            }catch(exception &ex) {
+                if( cnt > 0) {
                     //失败重试
-                    std::lock_guard<std::mutex> lk(_error_query_mutex);
-                    sqlQuery query(sql, cnt);
+                    lock_guard<mutex> lk(_error_query_mutex);
+                    sqlQuery query(sql,cnt);
                     _error_query.push_back(query);
-                } else {
-                    WarnL << "SqlPool::syncQuery failed: " << ex.what();
+                }else{
+                    WarnL <<  ex.what();
                 }
             }
         };
@@ -144,35 +145,32 @@ private:
     void flushError() {
         decltype(_error_query) query_copy;
         {
-            std::lock_guard<std::mutex> lck(_error_query_mutex);
+            lock_guard<mutex> lck(_error_query_mutex);
             query_copy.swap(_error_query);
         }
         for (auto &query : query_copy) {
-            asyncQuery(query.sql_str, query.tryCnt);
+            asyncQuery(query.sql_str,query.tryCnt);
         }
     }
 
     /**
      * 检查数据库连接池是否初始化
      */
-    void checkInited() {
-        if (!_pool) {
-            throw SqlException("SqlPool::checkInited", "Mysql connection pool not initialized");
+    void checkInited(){
+        if(!_pool){
+            throw SqlException("SqlPool::checkInited","数据库连接池未初始化");
         }
     }
-
 private:
     struct sqlQuery {
-        sqlQuery(const std::string &sql, int cnt) : sql_str(sql), tryCnt(cnt) {}
-
-        std::string sql_str;
+        sqlQuery(const string &sql,int cnt):sql_str(sql),tryCnt(cnt){}
+        string sql_str;
         int tryCnt = 0;
-    };
-
+    } ;
 private:
-    std::deque<sqlQuery> _error_query;
+    deque<sqlQuery> _error_query;
     TaskExecutor::Ptr _threadPool;
-    std::mutex _error_query_mutex;
+    mutex _error_query_mutex;
     std::shared_ptr<PoolType> _pool;
     Timer::Ptr _timer;
 };
@@ -182,36 +180,32 @@ private:
  */
 class SqlStream {
 public:
-    SqlStream(const char *sql) : _sql(sql) {}
-
+    SqlStream(const char *sql) : _sql(sql){}
     ~SqlStream() {}
 
     template<typename T>
-    SqlStream &operator<<(T &&data) {
+    SqlStream& operator <<(T &&data) {
         auto pos = _sql.find('?', _startPos);
-        if (pos == std::string::npos) {
+        if (pos == string::npos) {
             return *this;
         }
         _str_tmp.str("");
         _str_tmp << std::forward<T>(data);
-        std::string str = SqlPool::Instance().escape(_str_tmp.str());
+        string str = SqlPool::Instance().escape(_str_tmp.str());
         _startPos = pos + str.size();
         _sql.replace(pos, 1, str);
         return *this;
     }
-
-    const std::string &operator<<(std::ostream &(*f)(std::ostream &)) const {
+    const string& operator <<(std::ostream&(*f)(std::ostream&)) const {
         return _sql;
     }
-
-    operator std::string() {
+    operator string (){
         return _sql;
     }
-
 private:
-    std::stringstream _str_tmp;
-    std::string _sql;
-    std::string::size_type _startPos = 0;
+    stringstream _str_tmp;
+    string _sql;
+    string::size_type _startPos = 0;
 };
 
 
@@ -225,8 +219,7 @@ public:
      * @param sql 带'?'占位符的sql模板
      * @param throwAble 是否抛异常
      */
-    SqlWriter(const char *sql, bool throwAble = true) : _sqlstream(sql), _throwAble(throwAble) {}
-
+    SqlWriter(const char *sql,bool throwAble = true) : _sqlstream(sql),_throwAble(throwAble) {}
     ~SqlWriter() {}
 
     /**
@@ -236,14 +229,14 @@ public:
      * @return 本身引用
      */
     template<typename T>
-    SqlWriter &operator<<(T &&data) {
+    SqlWriter& operator <<(T &&data) {
         try {
             _sqlstream << std::forward<T>(data);
-        } catch (std::exception &ex) {
+        }catch (std::exception &ex){
             //在转义sql时可能抛异常
-            if (!_throwAble) {
-                WarnL << "Commit sql failed: " << ex.what();
-            } else {
+            if(!_throwAble){
+                WarnL << ex.what();
+            }else{
                 throw;
             }
         }
@@ -254,9 +247,9 @@ public:
      * 异步执行sql,不会抛异常
      * @param f std::endl
      */
-    void operator<<(std::ostream &(*f)(std::ostream &)) {
+    void operator <<(std::ostream&(*f)(std::ostream&)) {
         //异步执行sql不会抛异常
-        SqlPool::Instance().asyncQuery((std::string) _sqlstream);
+        SqlPool::Instance().asyncQuery((string)_sqlstream);
     }
 
     /**
@@ -266,13 +259,13 @@ public:
      * @param ret 数据存放对象
      * @return 影响行数
      */
-    template<typename Row>
-    int64_t operator<<(std::vector<Row> &ret) {
+    template <typename Row>
+    int64_t operator <<(vector<Row> &ret) {
         try {
-            _affectedRows = SqlPool::Instance().syncQuery(_rowId, ret, (std::string) _sqlstream);
-        } catch (std::exception &ex) {
-            if (!_throwAble) {
-                WarnL << "SqlPool::syncQuery failed: " << ex.what();
+            _affectedRows = SqlPool::Instance().syncQuery(_rowId,ret, (string)_sqlstream);
+        }catch (std::exception &ex){
+            if(!_throwAble){
+                WarnL << ex.what();
             } else {
                 throw;
             }
@@ -295,7 +288,6 @@ public:
     int64_t getAffectedRows() const {
         return _affectedRows;
     }
-
 private:
     SqlStream _sqlstream;
     int64_t _rowId = -1;

+ 18 - 17
3rdparty/ZLToolKit/include/Util/TimeTicker.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,8 +11,9 @@
 #ifndef UTIL_TIMETICKER_H_
 #define UTIL_TIMETICKER_H_
 
-#include <cassert>
+#include <assert.h>
 #include "logger.h"
+#include "Util/util.h"
 
 namespace toolkit {
 
@@ -25,7 +26,7 @@ public:
      * @param print_log 是否打印代码执行时间
      */
     Ticker(uint64_t min_ms = 0,
-           LogContextCapture ctx = LogContextCapture(Logger::Instance(), LWarn, __FILE__, "", __LINE__),
+           LogContextCapturer ctx = LogContextCapturer(Logger::Instance(), LWarn, __FILE__, "", __LINE__),
            bool print_log = false) : _ctx(std::move(ctx)) {
         if (!print_log) {
             _ctx.clear();
@@ -37,21 +38,21 @@ public:
     ~Ticker() {
         uint64_t tm = createdTime();
         if (tm > _min_ms) {
-            _ctx << "take time: " << tm << "ms" << ", thread may be overloaded";
+            _ctx << "take time:" << tm << "ms" << ", thread may be overloaded";
         } else {
             _ctx.clear();
         }
     }
 
     /**
-     * 获取上次resetTime后至今的时间,单位毫秒
+     * 获取创建时间,单位毫秒
      */
     uint64_t elapsedTime() const {
         return getCurrentMillisecond() - _begin;
     }
 
     /**
-     * 获取从创建至今的时间,单位毫秒
+     * 获取上次resetTime后至今的时间,单位毫秒
      */
     uint64_t createdTime() const {
         return getCurrentMillisecond() - _created;
@@ -68,7 +69,7 @@ private:
     uint64_t _min_ms;
     uint64_t _begin;
     uint64_t _created;
-    LogContextCapture _ctx;
+    LogContextCapturer _ctx;
 };
 
 class SmoothTicker {
@@ -95,8 +96,8 @@ public:
                 double elapse_time = (now_time - last_time);
                 _time_inc += (elapse_time / ++_pkt_count) / 3;
                 auto ret_time = last_time + _time_inc;
-                _last_time = (uint64_t) ret_time;
-                return (uint64_t) ret_time;
+                _last_time = (uint64_t)ret_time;
+                return (uint64_t)ret_time;
             }
             _first_time = now_time;
             _last_time = now_time;
@@ -111,8 +112,8 @@ public:
         if (elapse_time > _reset_ms) {
             _first_time = 0;
         }
-        _last_time = (uint64_t) ret_time;
-        return (uint64_t) ret_time;
+        _last_time = (uint64_t)ret_time;
+        return (uint64_t)ret_time;
     }
 
     /**
@@ -134,13 +135,13 @@ private:
 };
 
 #if !defined(NDEBUG)
-#define TimeTicker() Ticker __ticker(5,WarnL,true)
-#define TimeTicker1(tm) Ticker __ticker1(tm,WarnL,true)
-#define TimeTicker2(tm, log) Ticker __ticker2(tm,log,true)
+    #define TimeTicker() Ticker __ticker(5,WarnL,true)
+    #define TimeTicker1(tm) Ticker __ticker1(tm,WarnL,true)
+    #define TimeTicker2(tm,log) Ticker __ticker2(tm,log,true)
 #else
-#define TimeTicker()
-#define TimeTicker1(tm)
-#define TimeTicker2(tm,log)
+    #define TimeTicker()
+    #define TimeTicker1(tm)
+    #define TimeTicker2(tm,log)
 #endif
 
 } /* namespace toolkit */

+ 4 - 3
3rdparty/ZLToolKit/include/Util/base64.h

@@ -22,8 +22,9 @@
 #ifndef AVUTIL_BASE64_H
 #define AVUTIL_BASE64_H
 
-#include <cstdint>
+#include <stdint.h>
 #include <string>
+using namespace std;
 
 /**
  * Decode a base64-encoded string.
@@ -59,13 +60,13 @@ char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size);
  * @param txt 明文
  * @return 密文
  */
-std::string encodeBase64(const std::string &txt);
+string encodeBase64(const string &txt);
 
 /**
  * 解码base64
  * @param txt 密文
  * @return 明文
  */
-std::string decodeBase64(const std::string &txt);
+string decodeBase64(const string &txt);
 
 #endif /* AVUTIL_BASE64_H */

+ 1 - 1
3rdparty/ZLToolKit/include/Util/function_traits.h

@@ -2,7 +2,7 @@
 #define SRC_UTIL_FUNCTION_TRAITS_H_
 
 #include <tuple>
-#include <functional>
+using namespace std;
 
 namespace toolkit {
 

+ 64 - 157
3rdparty/ZLToolKit/include/Util/logger.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -11,17 +11,24 @@
 #ifndef UTIL_LOGGER_H_
 #define UTIL_LOGGER_H_
 
-#include <cstdarg>
+#include <time.h>
+#include <stdio.h>
+#include <string.h>
 #include <set>
 #include <map>
+#include <deque>
+#include <iostream>
 #include <fstream>
+#include <sstream>
 #include <thread>
 #include <memory>
 #include <mutex>
-#include "util.h"
-#include "List.h"
+#include "Util/util.h"
+#include "Util/List.h"
 #include "Thread/semaphore.h"
 
+using namespace std;
+
 namespace toolkit {
 
 class LogContext;
@@ -29,8 +36,7 @@ class LogChannel;
 class LogWriter;
 class Logger;
 
-using LogContextPtr = std::shared_ptr<LogContext>;
-
+typedef std::shared_ptr<LogContext> LogContextPtr;
 typedef enum {
     LTrace = 0, LDebug, LInfo, LWarn, LError
 } LogLevel;
@@ -44,7 +50,7 @@ void setLogger(Logger *logger);
 class Logger : public std::enable_shared_from_this<Logger>, public noncopyable {
 public:
     friend class AsyncLogWriter;
-    using Ptr = std::shared_ptr<Logger>;
+    typedef std::shared_ptr<Logger> Ptr;
 
     /**
      * 获取日志单例
@@ -52,7 +58,7 @@ public:
      */
     static Logger &Instance();
 
-    explicit Logger(const std::string &loggerName);
+    Logger(const string &loggerName);
     ~Logger();
 
     /**
@@ -65,14 +71,14 @@ public:
      * 删除日志通道,非线程安全的
      * @param name log通道名
      */
-    void del(const std::string &name);
+    void del(const string &name);
 
     /**
      * 获取日志通道,非线程安全的
      * @param name log通道名
      * @return 线程通道
      */
-    std::shared_ptr<LogChannel> get(const std::string &name);
+    std::shared_ptr<LogChannel> get(const string &name);
 
     /**
      * 设置写log器,非线程安全的
@@ -90,7 +96,7 @@ public:
      * 获取logger名
      * @return logger名
      */
-    const std::string &getName() const;
+    const string &getName() const;
 
     /**
      * 写日志
@@ -104,64 +110,52 @@ private:
      * @param ctx 日志信息
      */
     void writeChannels(const LogContextPtr &ctx);
-    void writeChannels_l(const LogContextPtr &ctx);
 
 private:
-    LogContextPtr _last_log;
-    std::string _logger_name;
+    map<string, std::shared_ptr<LogChannel> > _channels;
     std::shared_ptr<LogWriter> _writer;
-    std::map<std::string, std::shared_ptr<LogChannel> > _channels;
+    string _loggerName;
 };
 
 ///////////////////LogContext///////////////////
 /**
 * 日志上下文
 */
-class LogContext : public std::ostringstream {
+class LogContext : public ostringstream {
 public:
     //_file,_function改成string保存,目的是有些情况下,指针可能会失效
     //比如说动态库中打印了一条日志,然后动态库卸载了,那么指向静态数据区的指针就会失效
-    LogContext() = default;
-    LogContext(LogLevel level, const char *file, const char *function, int line, const char *module_name, const char *flag);
+
+    LogContext(LogLevel level, const char *file, const char *function, int line);
     ~LogContext() = default;
 
     LogLevel _level;
     int _line;
-    int _repeat = 0;
-    std::string _file;
-    std::string _function;
-    std::string _thread_name;
-    std::string _module_name;
-    std::string _flag;
+    string _file;
+    string _function;
+    string _thread_name;
     struct timeval _tv;
-
-    const std::string &str();
-
-private:
-    bool _got_content = false;
-    std::string _content;
 };
 
 /**
  * 日志上下文捕获器
  */
-class LogContextCapture {
+class LogContextCapturer {
 public:
-    using Ptr = std::shared_ptr<LogContextCapture>;
-
-    LogContextCapture(Logger &logger, LogLevel level, const char *file, const char *function, int line, const char *flag = "");
-    LogContextCapture(const LogContextCapture &that);
-    ~LogContextCapture();
+    typedef std::shared_ptr<LogContextCapturer> Ptr;
+    LogContextCapturer(Logger &logger, LogLevel level, const char *file, const char *function, int line);
+    LogContextCapturer(const LogContextCapturer &that);
+    ~LogContextCapturer();
 
     /**
      * 输入std::endl(回车符)立即输出日志
      * @param f std::endl(回车符)
      * @return 自身引用
      */
-    LogContextCapture &operator<<(std::ostream &(*f)(std::ostream &));
+    LogContextCapturer &operator<<(ostream &(*f)(ostream &));
 
     template<typename T>
-    LogContextCapture &operator<<(T &&data) {
+    LogContextCapturer &operator<<(T &&data) {
         if (!_ctx) {
             return *this;
         }
@@ -183,9 +177,8 @@ private:
  */
 class LogWriter : public noncopyable {
 public:
-    LogWriter() = default;
-    virtual ~LogWriter() = default;
-
+    LogWriter() {}
+    virtual ~LogWriter() {}
     virtual void write(const LogContextPtr &ctx, Logger &logger) = 0;
 };
 
@@ -201,10 +194,10 @@ private:
 
 private:
     bool _exit_flag;
+    mutex _mutex;
     semaphore _sem;
-    std::mutex _mutex;
-    std::shared_ptr<std::thread> _thread;
-    List<std::pair<LogContextPtr, Logger *> > _pending;
+    std::shared_ptr<thread> _thread;
+    List<std::pair<LogContextPtr,Logger *> > _pending;
 };
 
 ///////////////////LogChannel///////////////////
@@ -213,11 +206,11 @@ private:
  */
 class LogChannel : public noncopyable {
 public:
-    LogChannel(const std::string &name, LogLevel level = LTrace);
+    LogChannel(const string &name, LogLevel level = LTrace);
     virtual ~LogChannel();
 
     virtual void write(const Logger &logger, const LogContextPtr &ctx) = 0;
-    const std::string &name() const;
+    const string &name() const;
     void setLevel(LogLevel level);
     static std::string printTime(const timeval &tv);
 
@@ -225,40 +218,23 @@ protected:
     /**
     * 打印日志至输出流
     * @param ost 输出流
-    * @param enable_color 是否启用颜色
-    * @param enable_detail 是否打印细节(函数名、源码文件名、源码行)
+    * @param enableColor 是否启用颜色
+    * @param enableDetail 是否打印细节(函数名、源码文件名、源码行)
     */
-    virtual void format(const Logger &logger, std::ostream &ost, const LogContextPtr &ctx, bool enable_color = true, bool enable_detail = true);
+    virtual void format(const Logger &logger, ostream &ost, const LogContextPtr &ctx, bool enableColor = true, bool enableDetail = true);
 
 protected:
-    std::string _name;
+    string _name;
     LogLevel _level;
 };
 
 /**
- * 输出日至到广播
- */
-class EventChannel : public LogChannel {
-public:
-    //输出日志时的广播名
-    static const std::string kBroadcastLogEvent;
-    //日志广播参数类型和列表
-    #define BroadcastLogEventArgs const Logger &logger, const LogContextPtr &ctx
-
-    EventChannel(const std::string &name = "EventChannel", LogLevel level = LTrace);
-    ~EventChannel() override = default;
-
-    void write(const Logger &logger, const LogContextPtr &ctx) override;
-};
-
-/**
  * 输出日志至终端,支持输出日志至android logcat
  */
 class ConsoleChannel : public LogChannel {
 public:
-    ConsoleChannel(const std::string &name = "ConsoleChannel", LogLevel level = LTrace);
-    ~ConsoleChannel() override = default;
-
+    ConsoleChannel(const string &name = "ConsoleChannel", LogLevel level = LTrace);
+    ~ConsoleChannel();
     void write(const Logger &logger, const LogContextPtr &logContext) override;
 };
 
@@ -267,12 +243,12 @@ public:
  */
 class FileChannelBase : public LogChannel {
 public:
-    FileChannelBase(const std::string &name = "FileChannelBase", const std::string &path = exePath() + ".log", LogLevel level = LTrace);
-    ~FileChannelBase() override;
+    FileChannelBase(const string &name = "FileChannelBase", const string &path = exePath() + ".log", LogLevel level = LTrace);
+    ~FileChannelBase();
 
     void write(const Logger &logger, const LogContextPtr &ctx) override;
-    bool setPath(const std::string &path);
-    const std::string &path() const;
+    bool setPath(const string &path);
+    const string &path() const;
 
 protected:
     virtual bool open();
@@ -280,8 +256,8 @@ protected:
     virtual size_t size();
 
 protected:
-    std::string _path;
-    std::ofstream _fstream;
+    string _path;
+    ofstream _fstream;
 };
 
 class Ticker;
@@ -292,8 +268,8 @@ class Ticker;
  */
 class FileChannel : public FileChannelBase {
 public:
-    FileChannel(const std::string &name = "FileChannel", const std::string &dir = exeDir() + "log/", LogLevel level = LTrace);
-    ~FileChannel() override = default;
+    FileChannel(const string &name = "FileChannel", const string &dir = exeDir() + "log/", LogLevel level = LTrace);
+    ~FileChannel() override;
 
     /**
      * 写日志时才会触发新建日志文件或者删除老的日志文件
@@ -348,95 +324,26 @@ private:
     size_t _index = 0;
     int64_t _last_day = -1;
     time_t _last_check_time = 0;
-    std::string _dir;
-    std::set<std::string> _log_file_map;
+    string _dir;
+    set<string> _log_file_map;
 };
 
 #if defined(__MACH__) || ((defined(__linux) || defined(__linux__)) && !defined(ANDROID))
 class SysLogChannel : public LogChannel {
 public:
-    SysLogChannel(const std::string &name = "SysLogChannel", LogLevel level = LTrace);
-    ~SysLogChannel() override = default;
-
-    void write(const Logger &logger, const LogContextPtr &logContext) override;
+    SysLogChannel(const string &name = "SysLogChannel" , LogLevel level = LTrace) ;
+    ~SysLogChannel();
+    void write(const Logger &logger , const LogContextPtr &logContext) override;
 };
-
 #endif//#if defined(__MACH__) || ((defined(__linux) || defined(__linux__)) &&  !defined(ANDROID))
 
-class BaseLogFlagInterface {
-protected:
-    virtual ~BaseLogFlagInterface() {}
-    // 获得日志标记Flag
-    const char* getLogFlag(){
-        return _log_flag;
-    }
-    void setLogFlag(const char *flag) { _log_flag = flag; }
-private:
-    const char *_log_flag = "";
-};
-
-class LoggerWrapper {
-public:
-    template<typename First, typename ...ARGS>
-    static inline void printLogArray(Logger &logger, LogLevel level, const char *file, const char *function, int line, First &&first, ARGS &&...args) {
-        LogContextCapture log(logger, level, file, function, line);
-        log << std::forward<First>(first);
-        appendLog(log, std::forward<ARGS>(args)...);
-    }
-
-    static inline void printLogArray(Logger &logger, LogLevel level, const char *file, const char *function, int line) {
-        LogContextCapture log(logger, level, file, function, line);
-    }
-
-    template<typename Log, typename First, typename ...ARGS>
-    static inline void appendLog(Log &out, First &&first, ARGS &&...args) {
-        out << std::forward<First>(first);
-        appendLog(out, std::forward<ARGS>(args)...);
-    }
-
-    template<typename Log>
-    static inline void appendLog(Log &out) {}
-
-    //printf样式的日志打印
-    static void printLog(Logger &logger, int level, const char *file, const char *function, int line, const char *fmt, ...);
-    static void printLogV(Logger &logger, int level, const char *file, const char *function, int line, const char *fmt, va_list ap);
-};
-
 //可重置默认值
 extern Logger *g_defaultLogger;
-
-//用法: DebugL << 1 << "+" << 2 << '=' << 3;
-#define WriteL(level) ::toolkit::LogContextCapture(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__)
-#define TraceL WriteL(::toolkit::LTrace)
-#define DebugL WriteL(::toolkit::LDebug)
-#define InfoL WriteL(::toolkit::LInfo)
-#define WarnL WriteL(::toolkit::LWarn)
-#define ErrorL WriteL(::toolkit::LError)
-
-//只能在虚继承BaseLogFlagInterface的类中使用
-#define WriteF(level) ::toolkit::LogContextCapture(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__, getLogFlag())
-#define TraceF WriteF(::toolkit::LTrace)
-#define DebugF WriteF(::toolkit::LDebug)
-#define InfoF WriteF(::toolkit::LInfo)
-#define WarnF WriteF(::toolkit::LWarn)
-#define ErrorF WriteF(::toolkit::LError)
-
-//用法: PrintD("%d + %s = %c", 1 "2", 'c');
-#define PrintLog(level, ...) ::toolkit::LoggerWrapper::printLog(::toolkit::getLogger(), level, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
-#define PrintT(...) PrintLog(::toolkit::LTrace, ##__VA_ARGS__)
-#define PrintD(...) PrintLog(::toolkit::LDebug, ##__VA_ARGS__)
-#define PrintI(...) PrintLog(::toolkit::LInfo, ##__VA_ARGS__)
-#define PrintW(...) PrintLog(::toolkit::LWarn, ##__VA_ARGS__)
-#define PrintE(...) PrintLog(::toolkit::LError, ##__VA_ARGS__)
-
-//用法: LogD(1, "+", "2", '=', 3);
-//用于模板实例化的原因,如果每次打印参数个数和类型不一致,可能会导致二进制代码膨胀
-#define LogL(level, ...) ::toolkit::LoggerWrapper::printLogArray(::toolkit::getLogger(), (LogLevel)level, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
-#define LogT(...) LogL(::toolkit::LTrace, ##__VA_ARGS__)
-#define LogD(...) LogL(::toolkit::LDebug, ##__VA_ARGS__)
-#define LogI(...) LogL(::toolkit::LInfo, ##__VA_ARGS__)
-#define LogW(...) LogL(::toolkit::LWarn, ##__VA_ARGS__)
-#define LogE(...) LogL(::toolkit::LError, ##__VA_ARGS__)
-
+#define TraceL LogContextCapturer(getLogger(), LTrace, __FILE__,__FUNCTION__, __LINE__)
+#define DebugL LogContextCapturer(getLogger(),LDebug, __FILE__,__FUNCTION__, __LINE__)
+#define InfoL LogContextCapturer(getLogger(),LInfo, __FILE__,__FUNCTION__, __LINE__)
+#define WarnL LogContextCapturer(getLogger(),LWarn,__FILE__, __FUNCTION__, __LINE__)
+#define ErrorL LogContextCapturer(getLogger(),LError,__FILE__, __FUNCTION__, __LINE__)
+#define WriteL(level) LogContextCapturer(getLogger(),level,__FILE__, __FUNCTION__, __LINE__)
 } /* namespace toolkit */
 #endif /* UTIL_LOGGER_H_ */

+ 49 - 78
3rdparty/ZLToolKit/include/Util/mini.h

@@ -21,28 +21,33 @@
 #ifndef UTIL_MINI_H
 #define UTIL_MINI_H
 
-#include <cctype>
 #include <map>
 #include <string>
 #include <vector>
 #include <fstream>
-#include "util.h"
+#include <cstring>
+#include <cassert>
+#include <iostream>
+#include <exception>
+#include "Util/util.h"
+using namespace std;
 
 namespace toolkit {
 
+
 template<typename key, typename variant>
-class mINI_basic : public std::map<key, variant> {
+class mINI_basic: public map<key, variant> {
     // Public API : existing map<> interface plus following methods
 public:
-    void parse(const std::string &text) {
+    void parse(const string &text) {
         // reset, split lines and parse
-        std::vector<std::string> lines = tokenize(text, "\n");
-        std::string symbol, tag;
-        for (auto &line : lines) {
+        vector<string> lines = tokenize(text, "\n");
+        string symbol, tag;
+        for (auto &line : lines){
             // trim blanks
             line = trim(line);
             // split line into tokens and parse tokens
-            if (line.empty() || line.front() == ';' || line.front() == '#') {
+            if(line.empty() || line.front() == ';' || line.front() == '#'){
                 continue;
             }
             if (line.size() >= 3 && line.front() == '[' && line.back() == ']') {
@@ -50,59 +55,50 @@ public:
             } else {
                 auto at = line.find('=');
                 symbol = trim(tag + "." + line.substr(0, at));
-                (*this)[symbol] = (at == std::string::npos ? std::string() : trim(line.substr(at + 1)));
+                (*this)[symbol] = (at == string::npos ? string() : trim(line.substr(at + 1)));
             }
         }
     }
-
-    void parseFile(const std::string &fileName = exePath() + ".ini") {
-        std::ifstream in(fileName, std::ios::in | std::ios::binary | std::ios::ate);
+    void parseFile(const string &fileName = exePath() + ".ini") {
+        ifstream in(fileName, ios::in | ios::binary | ios::ate);
         if (!in.good()) {
-            throw std::invalid_argument("Invalid ini file: " + fileName);
+            stringstream ss;
+            ss << "invalid ini file:" << fileName;
+            throw invalid_argument(ss.str());
         }
         auto size = in.tellg();
-        in.seekg(0, std::ios::beg);
-        std::string buf;
+        in.seekg(0, ios::beg);
+        string buf;
         buf.resize(size);
         in.read((char *) buf.data(), size);
         parse(buf);
     }
 
-    std::string dump(const std::string &header = "; auto-generated by mINI class {",
-                     const std::string &footer = "; } ---") const {
-        std::string front(header + (header.empty() ? "" : "\r\n")), output, tag;
-        std::vector<std::string> kv;
+    string dump(const string &header = "; auto-generated by mINI class {",
+            const string &footer = "; } ---") const {
+        string output(header + (header.empty() ? "" : "\r\n")), tag;
         for (auto &pr : *this) {
-            auto pos = pr.first.find('.');
-            if (pos == std::string::npos) {
-                kv = {"", pr.first};
-            } else {
-                kv = {pr.first.substr(0, pos), pr.first.substr(pos + 1)};
-            }
-            if (kv[0].empty()) {
-                front += kv[1] + "=" + pr.second + "\r\n";
-                continue;
-            }
+            vector<string> kv = tokenize(pr.first, ".");
             if (tag != kv[0]) {
                 output += "\r\n[" + (tag = kv[0]) + "]\r\n";
             }
             output += kv[1] + "=" + pr.second + "\r\n";
         }
-        return front + output + "\r\n" + footer + (footer.empty() ? "" : "\r\n");
+        return output + "\r\n" + footer + (footer.empty() ? "" : "\r\n");
     }
 
-    void dumpFile(const std::string &fileName = exePath() + ".ini") {
-        std::ofstream out(fileName, std::ios::out | std::ios::binary | std::ios::trunc);
+    void dumpFile(const string &fileName = exePath() + ".ini") {
+        ofstream out(fileName, ios::out | ios::binary | ios::trunc);
         auto dmp = dump();
-        out.write(dmp.data(), dmp.size());
+        out.write(dmp.data(),dmp.size());
     }
 
     static mINI_basic &Instance();
 
 private:
-    std::vector<std::string> tokenize(const std::string &self, const std::string &chars) const {
-        std::vector<std::string> tokens(1);
-        std::string map(256, '\0');
+    vector<string> tokenize(const string &self, const string &chars) const {
+        vector<string> tokens(1);
+        string map(256, '\0');
         for (char ch : chars) {
             map[(uint8_t) ch] = '\1';
         }
@@ -110,7 +106,7 @@ private:
             if (!map.at((uint8_t) ch)) {
                 tokens.back().push_back(ch);
             } else if (tokens.back().size()) {
-                tokens.push_back(std::string());
+                tokens.push_back(string());
             }
         }
         while (tokens.size() && tokens.back().empty()) {
@@ -121,65 +117,40 @@ private:
 };
 
 //  handy variant class as key/values
-struct variant : public std::string {
+struct variant: public string {
     template<typename T>
     variant(const T &t) :
-            std::string(std::to_string(t)) {
+    string(to_string(t)) {
     }
-
     template<size_t N>
     variant(const char (&s)[N]) :
-            std::string(s, N) {
+    string(s, N) {
     }
-
     variant(const char *cstr) :
-            std::string(cstr) {
+        string(cstr) {
     }
-
-    variant(const std::string &other = std::string()) :
-            std::string(other) {
+    variant(const string &other = string()) :
+        string(other) {
     }
-
-    template <typename T>
+    template<typename T>
     operator T() const {
-        return as<T>();
+        T t;
+        stringstream ss;
+        return ss << *this && ss >> t ? t : T();
     }
-
-    template<typename T>
-    bool operator==(const T &t) const {
+    template<typename T> bool operator ==(const T &t) const {
         return 0 == this->compare(variant(t));
     }
-
-    bool operator==(const char *t) const {
+    bool operator ==(const char *t) const {
         return this->compare(t) == 0;
     }
-
-    template <typename T>
-    typename std::enable_if<!std::is_class<T>::value, T>::type as() const {
-        return as_default<T>();
-    }
-
-    template <typename T>
-    typename std::enable_if<std::is_class<T>::value, T>::type as() const {
-        return T((const std::string &)*this);
-    }
-
-private:
-    template <typename T>
-    T as_default() const {
-        T t;
-        std::stringstream ss;
-        return ss << *this && ss >> t ? t : T();
+    template<typename T>
+    T as() const {
+        return (T) (*this);
     }
 };
 
-template <>
-bool variant::as<bool>() const;
-
-template <>
-uint8_t variant::as<uint8_t>() const;
-
-using mINI = mINI_basic<std::string, variant>;
+using mINI = mINI_basic<string, variant>;
 
 }  // namespace toolkit
 #endif //UTIL_MINI_H

+ 12 - 11
3rdparty/ZLToolKit/include/Util/onceToken.h

@@ -1,32 +1,33 @@
 /*
-* Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
-*
-* This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
-*
-* Use of this source code is governed by MIT license that can be found in the
-* LICENSE file in the root of the source tree. All contributing project authors
-* may be found in the AUTHORS file in the root of the source tree.
-*/
+ * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
+ *
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
+ *
+ * Use of this source code is governed by MIT license that can be found in the
+ * LICENSE file in the root of the source tree. All contributing project authors
+ * may be found in the AUTHORS file in the root of the source tree.
+ */
 
 #ifndef UTIL_ONCETOKEN_H_
 #define UTIL_ONCETOKEN_H_
 
 #include <functional>
 #include <type_traits>
+using namespace std;
 
 namespace toolkit {
 
 class onceToken {
 public:
-    using task = std::function<void(void)>;
+    typedef function<void(void)> task;
 
     template<typename FUNC>
-    onceToken(const FUNC &onConstructed, task onDestructed = nullptr) {
+    onceToken(const FUNC &onConstructed, function<void(void)> onDestructed = nullptr) {
         onConstructed();
         _onDestructed = std::move(onDestructed);
     }
 
-    onceToken(std::nullptr_t, task onDestructed = nullptr) {
+    onceToken(nullptr_t, function<void(void)> onDestructed = nullptr) {
         _onDestructed = std::move(onDestructed);
     }
 

+ 44 - 155
3rdparty/ZLToolKit/include/Util/util.h

@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  *
- * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
+ * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  *
  * Use of this source code is governed by MIT license that can be found in the
  * LICENSE file in the root of the source tree. All contributing project authors
@@ -12,26 +12,25 @@
 #define UTIL_UTIL_H_
 
 #include <ctime>
-#include <cstdio>
-#include <cstring>
+#include <stdio.h>
+#include <string.h>
 #include <memory>
 #include <string>
 #include <sstream>
 #include <vector>
 #include <atomic>
 #include <unordered_map>
-#include "function_traits.h"
 #if defined(_WIN32)
 #undef FD_SETSIZE
 //修改默认64为1024路
 #define FD_SETSIZE 1024
-#include <winsock2.h>
+#include <WinSock2.h>
 #pragma comment (lib,"WS2_32")
 #else
 #include <unistd.h>
 #include <sys/time.h>
 #include <sys/types.h>
-#include <cstddef>
+#include <stddef.h>
 #endif // defined(_WIN32)
 
 #if defined(__APPLE__)
@@ -46,30 +45,32 @@
 #define INSTANCE_IMP(class_name, ...) \
 class_name &class_name::Instance() { \
     static std::shared_ptr<class_name> s_instance(new class_name(__VA_ARGS__)); \
-    static class_name &s_instance_ref = *s_instance; \
-    return s_instance_ref; \
+    static class_name &s_insteanc_ref = *s_instance; \
+    return s_insteanc_ref; \
 }
 
+using namespace std;
+
 namespace toolkit {
 
-#define StrPrinter ::toolkit::_StrPrinter()
-class _StrPrinter : public std::string {
+#define StrPrinter _StrPrinter()
+class _StrPrinter : public string {
 public:
     _StrPrinter() {}
 
     template<typename T>
     _StrPrinter& operator <<(T && data) {
         _stream << std::forward<T>(data);
-        this->std::string::operator=(_stream.str());
+        this->string::operator=(_stream.str());
         return *this;
     }
 
-    std::string operator <<(std::ostream&(*f)(std::ostream&)) const {
+    string operator <<(std::ostream&(*f)(std::ostream&)) const {
         return *this;
     }
 
 private:
-    std::stringstream _stream;
+    stringstream _stream;
 };
 
 //禁止拷贝基类
@@ -88,7 +89,7 @@ private:
 //可以保存任意的对象
 class Any{
 public:
-    using Ptr = std::shared_ptr<Any>;
+    typedef std::shared_ptr<Any> Ptr;
 
     Any() = default;
     ~Any() = default;
@@ -119,97 +120,34 @@ private:
 };
 
 //用于保存一些外加属性
-class AnyStorage : public std::unordered_map<std::string,Any>{
+class AnyStorage : public unordered_map<string,Any>{
 public:
     AnyStorage() = default;
     ~AnyStorage() = default;
-    using Ptr = std::shared_ptr<AnyStorage>;
+    typedef std::shared_ptr<AnyStorage> Ptr;
 };
 
-#ifndef CLASS_FUNC_TRAITS
-#define CLASS_FUNC_TRAITS(func_name) \
-template<typename T, typename ... ARGS> \
-constexpr bool Has_##func_name(decltype(&T::on##func_name) /*unused*/) { \
-    using RET = typename function_traits<decltype(&T::on##func_name)>::return_type; \
-    using FuncType = RET (T::*)(ARGS...);   \
-    return std::is_same<decltype(&T::on ## func_name), FuncType>::value; \
-} \
-\
-template<class T, typename ... ARGS> \
-constexpr bool Has_##func_name(...) { \
-    return false; \
-} \
-\
-template<typename T, typename ... ARGS> \
-static void InvokeFunc_##func_name(typename std::enable_if<!Has_##func_name<T, ARGS...>(nullptr), T>::type &obj, ARGS ...args) {} \
-\
-template<typename T, typename ... ARGS>\
-static typename function_traits<decltype(&T::on##func_name)>::return_type InvokeFunc_##func_name(typename std::enable_if<Has_##func_name<T, ARGS...>(nullptr), T>::type &obj, ARGS ...args) {\
-    return obj.on##func_name(std::forward<ARGS>(args)...);\
-}
-#endif //CLASS_FUNC_TRAITS
-
-#ifndef CLASS_FUNC_INVOKE
-#define CLASS_FUNC_INVOKE(T, obj, func_name, ...) InvokeFunc_##func_name<T>(obj, ##__VA_ARGS__)
-#endif //CLASS_FUNC_INVOKE
-
-CLASS_FUNC_TRAITS(Destory)
-CLASS_FUNC_TRAITS(Create)
-
-/**
- * 对象安全的构建和析构,构建后执行onCreate函数,析构前执行onDestory函数
- * 在函数onCreate和onDestory中可以执行构造或析构中不能调用的方法,比如说shared_from_this或者虚函数
- * @warning onDestory函数确保参数个数为0;否则会被忽略调用
- */
+//对象安全的构建和析构
+//构建后执行onCreate函数
+//析构前执行onDestory函数
+//在函数onCreate和onDestory中可以执行构造或析构中不能调用的方法,比如说shared_from_this或者虚函数
 class Creator {
 public:
-    /**
-     * 创建对象,用空参数执行onCreate和onDestory函数
-     * @param args 对象构造函数参数列表
-     * @return args对象的智能指针
-     */
-    template<typename C, typename ...ArgsType>
-    static std::shared_ptr<C> create(ArgsType &&...args) {
-        std::shared_ptr<C> ret(new C(std::forward<ArgsType>(args)...), [](C *ptr) {
-            try {
-                CLASS_FUNC_INVOKE(C, *ptr, Destory);
-            } catch (std::exception &ex){
-                onDestoryException(typeid(C), ex);
-            }
+    template<typename C,typename ...ArgsType>
+    static std::shared_ptr<C> create(ArgsType &&...args){
+        std::shared_ptr<C> ret(new C(std::forward<ArgsType>(args)...),[](C *ptr){
+            ptr->onDestory();
             delete ptr;
         });
-        CLASS_FUNC_INVOKE(C, *ret, Create);
+        ret->onCreate();
         return ret;
     }
-
-    /**
-     * 创建对象,用指定参数执行onCreate函数
-     * @param args 对象onCreate函数参数列表
-     * @warning args参数类型和个数必须与onCreate函数类型匹配(不可忽略默认参数),否则会由于模板匹配失败导致忽略调用
-     * @return args对象的智能指针
-     */
-    template<typename C, typename ...ArgsType>
-    static std::shared_ptr<C> create2(ArgsType &&...args) {
-        std::shared_ptr<C> ret(new C(), [](C *ptr) {
-            try {
-                CLASS_FUNC_INVOKE(C, *ptr, Destory);
-            } catch (std::exception &ex){
-                onDestoryException(typeid(C), ex);
-            }
-            delete ptr;
-        });
-        CLASS_FUNC_INVOKE(C, *ret, Create, std::forward<ArgsType>(args)...);
-        return ret;
-    }
-
-private:
-    static void onDestoryException(const std::type_info &info, const std::exception &ex);
-
 private:
     Creator() = default;
     ~Creator() = default;
 };
 
+
 template <class C>
 class ObjectStatistic{
 public:
@@ -226,27 +164,27 @@ public:
     }
 
 private:
-    static std::atomic<size_t> & getCounter();
+    static atomic<size_t> & getCounter();
 };
 
 #define StatisticImp(Type)  \
     template<> \
-    std::atomic<size_t>& ObjectStatistic<Type>::getCounter(){ \
-        static std::atomic<size_t> instance(0); \
+    atomic<size_t>& ObjectStatistic<Type>::getCounter(){ \
+        static atomic<size_t> instance(0); \
         return instance; \
     }
 
-std::string makeRandStr(int sz, bool printable = true);
-std::string hexdump(const void *buf, size_t len);
-std::string hexmem(const void* buf, size_t len);
-std::string exePath(bool isExe = true);
-std::string exeDir(bool isExe = true);
-std::string exeName(bool isExe = true);
+string makeRandStr(int sz, bool printable = true);
+string hexdump(const void *buf, size_t len);
+string hexmem(const void* buf, size_t len);
+string exePath();
+string exeDir();
+string exeName();
 
-std::vector<std::string> split(const std::string& s, const char *delim);
+vector<string> split(const string& s, const char *delim);
 //去除前后的空格、回车符、制表符...
-std::string& trim(std::string &s,const std::string &chars=" \r\n\t");
-std::string trim(std::string &&s,const std::string &chars=" \r\n\t");
+std::string& trim(std::string &s,const string &chars=" \r\n\t");
+std::string trim(std::string &&s,const string &chars=" \r\n\t");
 // string转小写
 std::string &strToLower(std::string &str);
 std::string strToLower(std::string &&str);
@@ -254,39 +192,13 @@ std::string strToLower(std::string &&str);
 std::string &strToUpper(std::string &str);
 std::string strToUpper(std::string &&str);
 //替换子字符串
-void replace(std::string &str, const std::string &old_str, const std::string &new_str, std::string::size_type b_pos = 0) ;
+void replace(string &str, const string &old_str, const string &new_str) ;
 //判断是否为ip
 bool isIP(const char *str);
 //字符串是否以xx开头
-bool start_with(const std::string &str, const std::string &substr);
+bool start_with(const string &str, const string &substr);
 //字符串是否以xx结尾
-bool end_with(const std::string &str, const std::string &substr);
-//拼接格式字符串
-template<typename... Args>
-std::string str_format(const std::string &format, Args... args) {
-#if __cplusplus > 202002L
-    return std::format(format, args...);
-#else
-    // Calculate the buffer size
-    auto size_buf = snprintf(nullptr, 0, format.c_str(), args ...) + 1;
-    // Allocate the buffer
-#if __cplusplus >= 201703L
-    // C++17
-    auto buf = std::make_unique<char[]>(size_buf);
-#else
-    // C++11
-    std:: unique_ptr<char[]> buf(new(std::nothrow) char[size_buf]);
-#endif
-    // Check if the allocation is successful
-    if (buf == nullptr) {
-        return {};
-    }
-    // Fill the buffer with formatted string
-    auto result = snprintf(buf.get(), size_buf, format.c_str(), args ...);
-    // Return the formatted string
-    return std::string(buf.get(), buf.get() + result);
-#endif
-}
+bool end_with(const string &str, const string &substr);
 
 #ifndef bzero
 #define bzero(ptr,size)  memset((ptr),0,(size));
@@ -305,7 +217,6 @@ std::string to_string(T value){
 int gettimeofday(struct timeval *tp, void *tzp);
 void usleep(int micro_seconds);
 void sleep(int second);
-int vasprintf(char **strp, const char *fmt, va_list ap);
 int asprintf(char **strp, const char *fmt, ...);
 const char *strcasestr(const char *big, const char *little);
 
@@ -323,11 +234,6 @@ const char *strcasestr(const char *big, const char *little);
 #endif //WIN32
 
 /**
- * 获取时间差, 返回值单位为秒
- */
-long getGMTOff();
-
-/**
  * 获取1970年至今的毫秒数
  * @param system_time 是否为系统时间(系统时间可以回退),否则为程序启动时间(不可回退)
  */
@@ -344,7 +250,7 @@ uint64_t getCurrentMicrosecond(bool system_time = false);
  * @param fmt 时间格式,譬如%Y-%m-%d %H:%M:%S
  * @return 时间字符串
  */
-std::string getTimeStr(const char *fmt,time_t time = 0);
+string getTimeStr(const char *fmt,time_t time = 0);
 
 /**
  * 根据unix时间戳获取本地时间
@@ -361,24 +267,7 @@ void setThreadName(const char *name);
 /**
  * 获取线程名
  */
-std::string getThreadName();
-
-/**
- * 设置当前线程cpu亲和性
- * @param i cpu索引,如果为-1,那么取消cpu亲和性
- * @return 是否成功,目前只支持linux
- */
-bool setThreadAffinity(int i);
-
-/**
- * 根据typeid(class).name()获取类名
- */
-std::string demangle(const char *mangled);
-
-/**
- * 获取环境变量内容,以'$'开头
- */
-std::string getEnv(const std::string &key);
+string getThreadName();
 
 }  // namespace toolkit
 #endif /* UTIL_UTIL_H_ */

+ 7 - 7
3rdparty/ZLToolKit/include/Util/uv_errno.h

@@ -22,7 +22,7 @@
 #ifndef UV_ERRNO_H_
 #define UV_ERRNO_H_
 
-#include <cerrno>
+#include <errno.h>
 
 #define UV__EOF     (-4095)
 #define UV__UNKNOWN (-4094)
@@ -502,8 +502,6 @@
   XX(EHOSTDOWN, "host is down")                                               \
   XX(EREMOTEIO, "remote I/O error")                                           \
 
-namespace toolkit {
-
 typedef enum {
 #define XX(code, _) UV_ ## code = UV__ ## code,
     UV_ERRNO_MAP(XX)
@@ -511,14 +509,16 @@ typedef enum {
     UV_ERRNO_MAX = UV__EOF - 1
 } uv_errno_t;
 
-const char *uv_err_name(int err);
-const char *uv_strerror(int err);
+
+const char* uv_err_name(int err);
+const char* uv_strerror(int err);
+
 int uv_translate_posix_error(int err);
 //netErr参数在windows平台下才有效
 int get_uv_error(bool netErr = true);
 //netErr参数在windows平台下才有效
-const char *get_uv_errmsg(bool netErr = true);
+const char* get_uv_errmsg(bool netErr = true);
+
 
-}//namespace toolkit
 
 #endif /* UV_ERRNO_H_ */

二进制
3rdparty/ZLToolKit/lib/libZLToolKit.a


二进制
3rdparty/ZLToolKit/lib/libZLToolKit.so


二进制
lib/libgsd_modules.so


二进制
lib/libgsd_plugins.so


+ 2 - 2
modules/Expel/src/Expel.cpp

@@ -69,9 +69,9 @@ namespace gsd
             //发送阻塞后,缓存清空事件
             DebugL;
         }
-        virtual void onError(const SockException &err) override{
+        virtual void onErr(const SockException &ex) override{
             //断开连接事件,一般是EOF
-            WarnL << err.what();
+            WarnL << ex.what();
             flag = false;
         }
         virtual void onManager() override{

+ 1 - 1
modules/TCPClient/include/TCPClient.hpp

@@ -95,7 +95,7 @@ namespace gsd
          * @return {*}
          * @author: lishengyin
          */   
-        virtual void onError(const SockException &err) override;
+        virtual void onErr(const SockException &ex) override;
             /**
          * @description: 心跳 2S触发一次
          * @param {*}

+ 2 - 2
modules/TCPClient/src/TCPClient.cpp

@@ -125,10 +125,10 @@ namespace gsd{
      * @return {*}
      * @author: lishengyin
      */    
-    void TCPClient::onError(const SockException &err){
+    void TCPClient::onErr(const SockException &ex){
         //断开连接事件,一般是EOF
         _nTick = 0;
-        ErrorL << err.what();
+        ErrorL << ex.what();
         // 广播数据
         NoticeCenter::Instance().emitEvent(NOTICE_DISCONNECT);
     }