SocketStream.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #pragma once
  2. #include <iostream>
  3. #include "TCPSocket.h"
  4. #include "TLSSocket.h"
  5. namespace bell {
  6. class SocketBuffer : public std::streambuf {
  7. private:
  8. std::unique_ptr<bell::Socket> internalSocket;
  9. static const int bufLen = 1024;
  10. char ibuf[bufLen], obuf[bufLen];
  11. public:
  12. SocketBuffer() { internalSocket = nullptr; }
  13. SocketBuffer(const std::string& hostname, int port, bool isSSL = false) {
  14. open(hostname, port);
  15. }
  16. int open(const std::string& hostname, int port, bool isSSL = false);
  17. int close();
  18. bool isOpen() {
  19. return internalSocket != nullptr && internalSocket->isOpen();
  20. }
  21. ~SocketBuffer() { close(); }
  22. protected:
  23. virtual int sync();
  24. virtual int_type underflow();
  25. virtual int_type overflow(int_type c = traits_type::eof());
  26. virtual std::streamsize xsgetn(char_type* __s, std::streamsize __n);
  27. virtual std::streamsize xsputn(const char_type* __s, std::streamsize __n);
  28. };
  29. class SocketStream : public std::iostream {
  30. private:
  31. SocketBuffer socketBuf;
  32. public:
  33. SocketStream() : std::iostream(&socketBuf) {}
  34. SocketStream(const std::string& hostname, int port, bool isSSL = false)
  35. : std::iostream(&socketBuf) {
  36. open(hostname, port, isSSL);
  37. }
  38. SocketBuffer* rdbuf() { return &socketBuf; }
  39. int open(const std::string& hostname, int port, bool isSSL = false) {
  40. int err = socketBuf.open(hostname, port, isSSL);
  41. if (err)
  42. setstate(std::ios::failbit);
  43. return err;
  44. }
  45. int close() { return socketBuf.close(); }
  46. bool isOpen() { return socketBuf.isOpen(); }
  47. };
  48. } // namespace bell