00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043 #ifndef _SOCKET_
00044 #define _SOCKET_
00045
00046 #ifdef SOCKET_STAT
00047 #include <time.h>
00048 #include <iostream>
00049 #endif
00050
00051 #include <sys/types.h>
00052 #include <unistd.h>
00053
00060 class Socket
00061 {
00062 protected:
00064 bool connected;
00066 int sockID;
00068 int error;
00069
00070 #ifdef SOCKET_STAT
00071 mutable long sentBytes;
00072 mutable long readBytes;
00073 mutable time_t startTime;
00074 #endif
00075
00076 public:
00078 Socket() : connected(false), sockID(-1), error(0) {
00079 #ifdef SOCKET_STAT
00080 sentBytes = 0;
00081 readBytes = 0;
00082 startTime = time(NULL);
00083 #endif
00084 }
00085
00094 Socket(int fd) : connected(true), sockID(fd), error(0) {
00095 #ifdef SOCKET_STAT
00096 sentBytes = 0;
00097 readBytes = 0;
00098 startTime = time(NULL);
00099 #endif
00100 }
00101
00108 int getError() { return error; }
00109
00111 int close() { return ::close(sockID); }
00112
00124 ssize_t read(void *buf, size_t nbytes) const
00125 {
00126 size_t len = 0;
00127 ssize_t n;
00128 char* ptr = (char*)buf;
00129
00130 while (len < nbytes) {
00131 n = ::read(sockID, ptr + len, nbytes - len);
00132 if(n < 0)
00133 return n;
00134
00135 len += n;
00136 }
00137
00138 #ifdef SOCKET_STAT
00139 readBytes += len;
00140 #endif
00141 return len;
00142 }
00143
00155 ssize_t write(const void *buf, size_t nbytes) const
00156 {
00157 #ifdef SOCKET_STAT
00158 sentBytes += nbytes;
00159 #endif
00160 return ::write(sockID, buf, nbytes);
00161 }
00162
00163 #ifdef SOCKET_STAT
00164 void writeStats(std::ostream& os) {
00165 static time_t lastTime = 0;
00166 static long lastRead = readBytes;
00167 static long lastSent = sentBytes;
00168 time_t now = time(NULL);
00169
00170 os << "Total bytes sent: " << sentBytes << std::endl
00171 << "Total bytes read: " << readBytes << std::endl
00172 << "Total time connected: " << now - startTime << std::endl;
00173
00174 if(lastTime == 0) {
00175 lastTime = now;
00176 lastRead = readBytes;
00177 lastSent = sentBytes;
00178 return;
00179 }
00180
00181 if(lastTime == now)
00182 return;
00183
00184 os << "RD Avg. since last stats: "
00185 << 1.0f*(readBytes - lastRead)/(now - lastTime) << std::endl
00186 << "WR Avg. since last stats: "
00187 << 1.0f*(sentBytes - lastSent)/(now - lastTime) << std::endl;
00188
00189 lastTime = now;
00190 lastRead = readBytes;
00191 lastSent = sentBytes;
00192 }
00193 #endif
00194 };
00195
00196 #endif //_SOCKET_