TcpSession.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef SERVER_SESSION_H_
  11. #define SERVER_SESSION_H_
  12. #include "Util/SSLBox.h"
  13. #include "Network/Session.h"
  14. using namespace std;
  15. namespace toolkit {
  16. //通过该模板可以让TCP服务器快速支持TLS
  17. template<typename TcpSessionType>
  18. class TcpSessionWithSSL : public TcpSessionType {
  19. public:
  20. template<typename ...ArgsType>
  21. TcpSessionWithSSL(ArgsType &&...args):TcpSessionType(std::forward<ArgsType>(args)...) {
  22. _ssl_box.setOnEncData([&](const Buffer::Ptr &buf) {
  23. public_send(buf);
  24. });
  25. _ssl_box.setOnDecData([&](const Buffer::Ptr &buf) {
  26. public_onRecv(buf);
  27. });
  28. }
  29. ~TcpSessionWithSSL() override{
  30. _ssl_box.flush();
  31. }
  32. void onRecv(const Buffer::Ptr &buf) override {
  33. _ssl_box.onRecv(buf);
  34. }
  35. //添加public_onRecv和public_send函数是解决较低版本gcc一个lambad中不能访问protected或private方法的bug
  36. inline void public_onRecv(const Buffer::Ptr &buf) {
  37. TcpSessionType::onRecv(buf);
  38. }
  39. inline void public_send(const Buffer::Ptr &buf) {
  40. TcpSessionType::send(std::move(const_cast<Buffer::Ptr &>(buf)));
  41. }
  42. protected:
  43. ssize_t send(Buffer::Ptr buf) override {
  44. auto size = buf->size();
  45. _ssl_box.onSend(buf);
  46. return size;
  47. }
  48. private:
  49. SSL_Box _ssl_box;
  50. };
  51. } /* namespace toolkit */
  52. #endif /* SERVER_SESSION_H_ */