Created
August 5, 2010 17:58
-
-
Save joshthecoder/510105 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Using the streaming API to pump data | |
read from a socket into a file. | |
*/ | |
// Assume we have opened both a socket and file. | |
var socket = ...; | |
var file = ...; | |
// First create a pump object to perform the transfer of data. | |
var pump = Titanium.createPump(socket, file); | |
// Install a Zlib deflate filter to un-compress incoming data | |
// before we write it into our file. | |
var deflateFilter = Titanium.Zlib.createDeflateFilter(); | |
pump.addFilter(deflateFilter); | |
// Notify us once the transfer has been completed. | |
// By default this occurs when the source object emits the "end" event. | |
// For sockets this would occur when the FIN packet is received. | |
// For files it would occur when the EOF is reached. | |
pump.on("finish", function() { //callback }); | |
// If an error where to occur during transfer, handle it with our callback. | |
pump.on("error", function(source, err) { | |
/* | |
source: object which caused the exception | |
This could be either the source, destination, or one of the filters. | |
Your callback can do == checks to determine what the source was for the error. | |
err: the exception that occurred | |
*/ | |
if (source == socket) { | |
alert("socket failed!!"); | |
} | |
else if (source == file) { | |
alert("file failed!!!"); | |
} | |
else if (source == deflateFilter) { | |
alert("Zlib filter failed!!"); | |
} | |
}); | |
// Let's say we need to advance a progress bar in our UI as data flows. | |
pump.on("flow", function(amount) { | |
// Assume we have defined an object which handles | |
// watching the progress of downloading which are being performed. | |
fileTransferWatcher.updateProgress(amount); | |
}); | |
// We have our pump all setup, callbacks attached, filter installed. | |
// Begin the transfer! | |
pump.start(); | |
// If we would want to pause the transfer with a button... | |
function pauseDownload() { | |
pump.pause(); | |
} | |
// To resume... | |
function resumeDownload() { | |
pump.resume(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment