Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@holdatlasfuk holdatlasfuk commented Mar 3, 2021

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

This comment has been minimized.

Copy link

@holdatlasfuk holdatlasfuk commented Mar 3, 2021

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

This comment has been minimized.

Copy link

@holdatlasfuk holdatlasfuk commented Mar 3, 2021

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