SocketStream.h 1.7 KB

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