Skip to content

Instantly share code, notes, and snippets.

@electricimp
Last active August 29, 2015 14:08
Show Gist options
  • Save electricimp/5d405f5f8129a38d9cb4 to your computer and use it in GitHub Desktop.
Save electricimp/5d405f5f8129a38d9cb4 to your computer and use it in GitHub Desktop.
Long Polling Agent HTTP Request Recipe
// Set up outgoing request object as a global (we may need to cancel it, so we need a reference to it)
request <- http.get(webServiceURL, webServiceHeaders)
// Define the response handler
function handleResponse(responseTable)
{
// Called when the imp receives an immediate acknowledgement from the remote service
if (responseTable.statuscode == 200)
{
// Remote service has responded with 'OK' so decode
// the response's body 'responseTable.body' and headers 'responseTable.headers'
// Code omitted for clarity
}
else
{
// Log an error
server.log("Error response: " + responseTable.statuscode)
// And cancel the request (since the remote server clearly can't fulfil the push request)
request.cancel()
}
}
// Define the long-poll response handler
function handleLongResponse(responseTable)
{
// Called when the imp receives a long-term response from the remote service
// This might be information 'pushed' to the device, so we need to re-submit
// the request in order to receive future notifications
if (responseTable.statuscode == 200)
{
// Remote service has responded with 'OK' so decode
// the response's body 'responseTable.body' and headers 'responseTable.headers'
// Code omitted for clarity
}
else
{
// Log an error
server.log("Error response: " + responseTable.statuscode)
}
// Re-submit the long-poll request. We must initialize a new request for this
request = http.get(webServiceURL, webServiceHeaders)
request.sendasync(handleResponse, handleLongResponse)
}
// Send the request asynchronously. This will not block the imp CPU
request.sendasync(handleResponse, handleLongResponse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment