00001
00002
00003
00004
00005
00006
00007
00008 #ifndef IBRCOMMON_TCPSTREAM_H_
00009 #define IBRCOMMON_TCPSTREAM_H_
00010
00011 #include "ibrcommon/Exceptions.h"
00012 #include <streambuf>
00013 #include <sys/types.h>
00014 #include <sys/socket.h>
00015 #include <iostream>
00016
00017 namespace ibrcommon
00018 {
00019 class ConnectionClosedException : public Exception
00020 {
00021 public:
00022 ConnectionClosedException(string what = "The connection has been closed.") throw() : Exception(what)
00023 {
00024 };
00025 };
00026
00027 class SocketException : public Exception
00028 {
00029 public:
00030 SocketException(string error) : Exception(error)
00031 {};
00032 };
00033
00034 class tcpstream : public std::basic_streambuf<char, std::char_traits<char> >, public std::iostream
00035 {
00036 public:
00037 enum stream_state {
00038 TCPSTREAM_CONNECTED = 0,
00039 TCPSTREAM_HALF_CLOSED = 1,
00040 TCPSTREAM_CLOSED = 2
00041 };
00042
00043 enum stream_error {
00044 ERROR_NONE = 0,
00045 ERROR_EPIPE = 1,
00046 ERROR_CLOSED = 2,
00047 ERROR_WRITE = 3,
00048 ERROR_READ = 4,
00049 ERROR_RESET = 5
00050 };
00051
00052
00053 static const size_t BUFF_SIZE = 2048;
00054
00055 tcpstream(int socket = 0);
00056 virtual ~tcpstream();
00057
00058 string getAddress() const;
00059 int getPort() const;
00060
00061 void close();
00062
00066 void done();
00067
00068 stream_error errmsg;
00069
00070 void enableKeepalive();
00071
00072 protected:
00073 virtual int sync();
00074 virtual int overflow(int = std::char_traits<char>::eof());
00075 virtual int underflow();
00076
00077 int _socket;
00078
00079 private:
00080 tcpstream(const tcpstream &s)
00081 : std::iostream(this), _socket(s._socket), _state(s._state) {};
00082
00083
00084 char *in_buf_;
00085
00086 char *out_buf_;
00087
00088 stream_state _state;
00089 };
00090 }
00091
00092 #endif