You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

peer.h 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /***********************************************
  2. File Name: peer.h
  3. Author: Abby Cin
  4. Mail: abbytsing@gmail.com
  5. Created Time: 10/24/20 2:42 PM
  6. ***********************************************/
  7. #ifndef _CONET_PEER_H_
  8. #define _CONET_PEER_H_
  9. class peer
  10. {
  11. public:
  12. peer(context& ctx, int fd) : ctx_{ctx}, fd_{fd} {}
  13. peer(peer&& r) noexcept : ctx_{r.ctx_}, fd_{r.fd_} { r.fd_ = -1; }
  14. ~peer() { this->close(); }
  15. auto read_some(char* data, int n)
  16. {
  17. struct awaiter
  18. {
  19. context& ctx_;
  20. int fd_;
  21. char* data_;
  22. int n_;
  23. awaiter(context& ctx, int f, char* data, int n) : ctx_{ctx}, fd_{f}, data_{data}, n_{n} {}
  24. bool await_ready() { return false; }
  25. bool await_suspend(handle_t co)
  26. {
  27. ctx_.push(fd_, co);
  28. return true; // same to `void await_suspend()`, immediately back to caller
  29. }
  30. int await_resume() { return ::read(fd_, data_, n_); }
  31. };
  32. return awaiter{ctx_, fd_, data, n};
  33. }
  34. // no guarantee that all data will be sent
  35. auto write_some(char* data, int n)
  36. {
  37. struct awaiter
  38. {
  39. peer* p_;
  40. int fd_;
  41. char* data_;
  42. int n_;
  43. int res_{0};
  44. awaiter(peer* p, int f, char* data, int n) : p_{p}, fd_{f}, data_{data}, n_{n} {}
  45. bool await_ready() { return false; }
  46. void await_suspend(handle_t) { res_ = ::write(fd_, data_, n_); }
  47. int await_resume() { return res_; }
  48. };
  49. return awaiter{this, fd_, data, n};
  50. }
  51. void close()
  52. {
  53. if(fd_ > 0)
  54. {
  55. ctx_.pop(fd_);
  56. ::close(fd_);
  57. fd_ = -1;
  58. }
  59. }
  60. private:
  61. context& ctx_;
  62. int fd_;
  63. };
  64. #endif //_CONET_PEER_H_