void TCPConnection::ThrowIfNotConnected_() { ConnectionState current_connection_state = connection_state_; if (current_connection_state != StateConnected) { throw DisconnectedException(); } }
ByteArray TCPSocket::read(size_t maxSize) { ByteArray ba(maxSize); // Return empty array if size is 0 if (maxSize == 0) { return ba; } // Read from socket ssize_t size = ::read(d->fd, ba.data(), ba.size()); // Check for errors if (size < 0) { switch (errno) { case EAGAIN: case ETIMEDOUT: throw TimeoutException("TCPSocket::read", strerror(errno)); case EPIPE: throw DisconnectedException("TCPSocket::read", strerror(errno)); default: throw IOException("TCPSocket::read", strerror(errno)); } } // If size is 0, means the socket is disconnected if (size == 0) { throw DisconnectedException("TCPSocket::read", "Disconnected"); } // Return a byte-array of the actual read size return ByteArray(ba.constData(), size); }
void TCPSocket::flush() { size_t sent = 0; while (sent < d->sendbuf.size()) { ssize_t size = ::write(d->fd, d->sendbuf.data(), d->sendbuf.size()); if (size < 0) { switch (errno) { case EAGAIN: case ETIMEDOUT: throw TimeoutException("TCPSocket::flush", strerror(errno)); case EPIPE: throw DisconnectedException("TCPSocket::flush", strerror(errno)); default: throw IOException("TCPSocket::flush", strerror(errno)); } } sent += size; } d->sendbuf.clear(); }
size_t InputStream::available(void) { const int socketFd = socket.getSocketFd(); // Using select for time being. Will research non-blocking IO in // due time. -- Gerjo fd_set fds; FD_ZERO(&fds); FD_SET(socketFd, &fds); int r = -1; // Sorry about this :( time constraints and stuff. if(_isBlocking) { // OK, this is a bummer situation. The timeout is required, else it will // keep on blocking forever. //cout << "[" << time(NULL) << "] Running select. Two second delay. " << endl; timeval timeout = {2, 0}; r = ::select(FD_SETSIZE, &fds, 0, 0, &timeout); } else { timeval timeout = {0, 0}; r = ::select(FD_SETSIZE, &fds, 0, 0, &timeout); } if (r == -1) { throw SocketException(strerror(errno)); } // Don't bother with anything. if(_isStopping) { return 0; } if(r == 0 && _isBlocking) { // symptom indicating the server may be offline. //throw SocketException("The server is offline or a SELECT() timeout was reached."); } if (FD_ISSET(socketFd, &fds)) { const int readChunkSize = 1024; char buff2[readChunkSize]; int bytesRead; do { bytesRead = ::recv(socketFd, reinterpret_cast<char*> (&buff2), readChunkSize, 0); // We can read no more data at this time. if (bytesRead == 0) { // Possibly check against errno == 0? This may be a genuine error. throw DisconnectedException(); } if (bytesRead == -1) { throw SocketException(strerror(errno)); } concatToBuffer(buff2, bytesRead); } while (bytesRead > readChunkSize); return buffer.size(); } return buffer.size(); }