1 // Sun, 18 Jun 2000 2 // Y.Takagi 3 4 #if defined(__HAIKU__) || defined(HAIKU_TARGET_PLATFORM_BONE) 5 # include <sys/socket.h> 6 #else 7 # include <net/socket.h> 8 #endif 9 10 #ifdef _DEBUG 11 #include <iostream> 12 #include <fstream> 13 #endif 14 15 #include "Socket.h" 16 #include "SocketStream.h" 17 18 /*-----------------------------------------------------------------*/ 19 20 socketstreambuf::socketstreambuf(Socket *sock, streamsize n) 21 : streambuf(), __sock(sock), __alsize(n), __pu(NULL), __po(NULL) 22 { 23 setg(0, 0, 0); 24 setp(0, 0); 25 } 26 27 socketstreambuf::~socketstreambuf() 28 { 29 if (__pu) 30 delete [] __pu; 31 if (__po) 32 delete [] __po; 33 } 34 35 int socketstreambuf::underflow() 36 { 37 // cout << "***** underflow" << endl; 38 39 int bytes; 40 41 if (__pu == NULL) { 42 __pu = new char[__alsize]; 43 } 44 45 bytes = __sock->read(__pu, __alsize); 46 if (bytes > 0) { 47 #ifdef _DEBUG 48 ofstream ofs("recv.log", ios::binary | ios::app); 49 ofs.write(__pu, bytes); 50 #endif 51 setg(__pu, __pu, __pu + bytes); 52 return *gptr(); 53 } 54 55 return EOF; 56 } 57 58 int socketstreambuf::overflow(int c) 59 { 60 // cout << "***** overflow" << endl; 61 62 if (__po == NULL) { 63 __po = new char[__alsize]; 64 setp(__po, __po + __alsize); 65 } else if (sync() != 0) { 66 return EOF; 67 } 68 return sputc(c); 69 } 70 71 int socketstreambuf::sync() 72 { 73 // cout << "***** sync" << endl; 74 75 if (__po) { 76 int length = pptr() - pbase(); 77 if (length > 0) { 78 const char *buffer = pbase(); 79 int bytes; 80 while (length > 0) { 81 bytes = __sock->write(buffer, length); 82 if (bytes <= 0) { 83 return EOF; 84 } 85 #ifdef _DEBUG 86 ofstream ofs("send.log", ios::binary | ios::app); 87 ofs.write(buffer, bytes); 88 #endif 89 length -= bytes; 90 buffer += bytes; 91 } 92 pbump(pbase() - pptr()); 93 } 94 } 95 96 return 0; 97 } 98 99 /* -------------------------------------------------------------- */ 100 101 socketstreambase::socketstreambase(Socket *sock, streamsize n) 102 : buf(sock, n) 103 { 104 ios::init(&this->buf); 105 } 106 107 /*-----------------------------------------------------------------*/ 108 109 isocketstream::isocketstream(Socket *sock, streamsize n) 110 : socketstreambase(sock, n), istream(socketstreambase::rdbuf()) 111 { 112 } 113 114 isocketstream::~isocketstream() 115 { 116 } 117 118 /*-----------------------------------------------------------------*/ 119 120 osocketstream::osocketstream(Socket *sock, streamsize n) 121 : socketstreambase(sock, n), ostream(socketstreambase::rdbuf()) 122 { 123 } 124 125 osocketstream::~osocketstream() 126 { 127 flush(); 128 } 129