Exemplo n.º 1
0
void TcpClientApp::onWrite( size_t bytesTransferred )
{
	mText.push_back( toString( bytesTransferred ) + " bytes written" );
	
	// After successfully sending your request to the server, you 
	// should expect a response. Start reading immediately.
	mSession->read();
}
Exemplo n.º 2
0
void WebClientApp::onRead( ci::BufferRef buffer )
{
	mText.push_back(toString( buffer->getSize() ) + " bytes read" );
	
	if ( !mHttpResponse.hasHeader() ) {
		mHttpResponse.parseHeader( HttpResponse::bufferToString( buffer ) );
		buffer = HttpResponse::removeHeader( buffer );
	}
	mHttpResponse.append( buffer );

	mSession->read();
}
Exemplo n.º 3
0
void WebClientApp::onWrite( size_t bytesTransferred )
{
	mText.push_back(toString( bytesTransferred ) + " bytes written" );
	mSession->read();
}
void HttpClientApp::onRead( ci::BufferRef buffer )
{
	size_t sz	= buffer->getSize();
	mBytesRead	+= sz;
	mText.push_back( toString( sz ) + " bytes read" );
	
	if ( !mHttpResponse.hasHeader() ) {
		
		// Parse header
		mHttpResponse.parseHeader( HttpResponse::bufferToString( buffer ) );
		buffer = HttpResponse::removeHeader( buffer );
		
		// Get content-length
		for ( const KeyValuePair& kvp : mHttpResponse.getHeaders() ) {
			if ( kvp.first == "Content-Length" ) {
				mContentLength = fromString<size_t>( kvp.second );
				break;
			}
		}
	}
	
	// Append buffer to body
	mHttpResponse.append( buffer );
	
	if ( mBytesRead < mContentLength ) {
		
		// Keep reading until we hit the content length
		mSession->read();
	} else {

		mText.push_back( "Read complete" );
		mText.push_back( toString( mHttpResponse.getStatusCode() ) + " " + mHttpResponse.getReason() );
		
		if ( mHttpResponse.getStatusCode() == 200 ) {
			for ( const KeyValuePair& kvp : mHttpResponse.getHeaders() ) {
				
				// Choose file extension based on MIME type
				if ( kvp.first == "Content-Type" ) {
					string mime = kvp.second;
					
					if ( mime == "audio/mp3" ) {
						mFilename += ".mp3";
					} else if ( mime == "image/jpeg" ) {
						mFilename += ".jpg";
					} else if ( mime == "image/png" ) {
						mFilename += ".png";
					}
				} else if ( kvp.first == "Connection" ) {
					
					// Close connection if requested by server
					if ( kvp.second == "close" ) {
						mSession->close();
					}
				}
			}

			// Save the file
			fs::path path = getAppPath();
#if !defined ( CINDER_MSW )
			path = path.parent_path();
#endif
			path = path / mFilename;
			OStreamFileRef file = writeFileStream( path );
			file->write( mHttpResponse.getBody() );
			
			mText.push_back( mFilename + " downloaded" );
		} else {
			
			// Write error
			mText.push_back( "Response: " +  HttpResponse::bufferToString( mHttpResponse.getBody() ) );
			
			mSession->close();
		}
	}
}