Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Created June 8, 2013 22:36
Show Gist options
  • Save igrigorik/5736866 to your computer and use it in GitHub Desktop.
Save igrigorik/5736866 to your computer and use it in GitHub Desktop.
XHR streaming example
<p>Hello
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/stream');
xhr.seenBytes = 0;
xhr.onreadystatechange = function() {
console.log("state change.. state: "+ xhr.readyState);
if(xhr.readyState == 3) {
var newData = xhr.response.substr(xhr.seenBytes);
console.log("newData: <<" +newData+ ">>");
document.body.innerHTML += "New data: <<" +newData+ ">><br />";
xhr.seenBytes = xhr.responseText.length;
console.log("seenBytes: " +xhr.seenBytes);
}
};
xhr.addEventListener("error", function(e) {
console.log("error: " +e);
});
console.log(xhr);
xhr.send();
</script>
require 'goliath'
class Server < Goliath::API
def response(env)
case env['REQUEST_PATH']
when /index/ then
[200, {}, IO.read('index.html')]
when /stream/ then
EM.add_periodic_timer(3) do
env.stream_send("data event! ... ")
end
headers = {'Content-Type' => 'application/x-javascript'}
[200, headers, Goliath::Response::STREAMING]
end
end
end
@holdatlasfuk
Copy link

Hello <script> var xhr = new XMLHttpRequest(); xhr.open('GET', '/stream'); xhr.seenBytes = 0; xhr.onreadystatechange = function() { console.log("state change.. state: "+ xhr.readyState); if(xhr.readyState == 3) { var newData = xhr.response.substr(xhr.seenBytes); console.log("newData: <<" +newData+ ">>"); document.body.innerHTML += "New data: <<" +newData+ ">>
"; xhr.seenBytes = xhr.responseText.length; console.log("seenBytes: " +xhr.seenBytes); } }; xhr.addEventListener("error", function(e) { console.log("error: " +e); }); console.log(xhr); xhr.send(); </script>

@holdatlasfuk
Copy link

require 'goliath'

class Server < Goliath::API

def response(env)
case env['REQUEST_PATH']
when /index/ then
[200, {}, IO.read('index.html')]

when /stream/ then
  EM.add_periodic_timer(3) do
    env.stream_send("data event! ... ")
  end

  headers = {'Content-Type' => 'application/x-javascript'}
  [200, headers, Goliath::Response::STREAMING]
end

end
end

@holdatlasfuk
Copy link

require 'goliath'

class Server < Goliath::API

def response(env)
case env['REQUEST_PATH']
when /index/ then
[200, {}, IO.read('index.html')]

when /stream/ then
EM.add_periodic_timer(3) do
env.stream_send("data event! ... ")
end

headers = {'Content-Type' => 'application/x-javascript'}
[200, headers, Goliath::Response::STREAMING]
end
end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment