// ---------------------------------------------------------------------- vector<unsigned char> SocketNs3:: receive(int bufSize) throw(SocketException) { vector<unsigned char> b; if (socket_ < 0) connect(); if (!datawaiting(socket_)) return b; unsigned char* buf = new unsigned char[bufSize]; int a = recv(socket_, (char*)buf, bufSize, 0); if (a <= 0) BailOnSocketError("SocketNs3::receive() @ recv"); b.resize(a); for (int i = 0; i < a; ++i) { b[i] = buf[i]; } if (verbose_) { cerr << "Rcvd " << a << " bytes via SocketNs3: ["; for (int i = 0; i < a; ++i) { cerr << " " << (int)b[i] << " "; } cerr << "]" << endl; } delete[] buf; return b; }
void Connection::pump() { if( m_Outstanding.empty() ) return; // no requests outstanding if (m_Sock < 0) { throw Wobbly("Pumping unconnected socket."); } //assert( m_Sock >0 ); // outstanding requests but no connection! if( !datawaiting( m_Sock ) ) return; // recv will block unsigned char buf[ 2048 ]; int a = recv( m_Sock, (char*)buf, sizeof(buf), 0 ); if( a<0 ) BailOnSocketError( "recv()" ); if( a== 0 ) { // connection has closed Response* r = m_Outstanding.front(); r->notifyconnectionclosed(); assert( r->completed() ); delete r; m_Outstanding.pop_front(); // any outstanding requests will be discarded close(); } else { int used = 0; while( used < a && !m_Outstanding.empty() ) { Response* r = m_Outstanding.front(); int u = r->pump( &buf[used], a-used ); // delete response once completed if( r->completed() ) { delete r; m_Outstanding.pop_front(); } used += u; } // NOTE: will lose bytes if response queue goes empty // (but server shouldn't be sending anything if we don't have // anything outstanding anyway) assert( used == a ); // all bytes should be used up by here. } }
// ---------------------------------------------------------------------- vector<unsigned char> NetStreamSocket:: receive(int bufSize) throw( NetStreamSocketException ) { vector<unsigned char> b; if( socket_ < 0 ) connect(); if( !datawaiting( socket_) ) return b; unsigned char const * const buf = new unsigned char[bufSize]; int a = recv( socket_, (char*)buf, bufSize, 0 ); if( a <= 0 ) { // BailOnNetStreamSocketError definitely throws an exception so clear up heap delete[] buf; BailOnNetStreamSocketError( "netstream::NetStreamSocket::receive() @ recv" ); } b.resize(a); for(int i = 0; i < a; ++i) { b[i] = buf[i]; } if (verbose_) { cerr << "Rcvd " << a << " bytes via netstream::NetStreamSocket: ["; for(int i = 0; i < a; ++i) { cerr << " " << (int)b[i] << " "; } cerr << "]" << endl; } delete[] buf; return b; }