Skip to content

Instantly share code, notes, and snippets.

@sh7ning
Last active December 3, 2018 06:18
Show Gist options
  • Save sh7ning/bb1a4d59929b3d3c726b6e73b121d954 to your computer and use it in GitHub Desktop.
Save sh7ning/bb1a4d59929b3d3c726b6e73b121d954 to your computer and use it in GitHub Desktop.
XHR stream read write example
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/stream');
xhr.seenBytes = 0;
xhr.onreadystatechange = function() {
if(xhr.readyState == 3) {
var newData = xhr.response.substr(xhr.seenBytes);
console.log(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);
});
xhr.send();
</script>
package main
import (
"net/http"
"log"
"fmt"
"time"
)
func output(w http.ResponseWriter, val interface{}) {
fmt.Fprintf(w, "%v", val)
w.(http.Flusher).Flush()
time.Sleep(time.Duration(1) * time.Second)
}
func stream(w http.ResponseWriter, r *http.Request) {
//see: https://stackoverflow.com/questions/26335228/go-flush-doesnt-work
//The issue is that Chrome's plain text renderer waits for the complete response body before displaying anything.
w.Header().Set("Content-Type", "text/html;charset=utf-8")
//必须有3个字符(如: abc)以上,js才开始获取到
output(w, "(counting to 3), Begin:")
for i := 0 ; i < 3; i++ {
output(w, i+1)
}
output(w, "End.")
}
func index(w http.ResponseWriter, r *http.Request) {
fmt.Println("index..")
index := "./index.html"
http.ServeFile(w, r, index)
}
func main() {
http.HandleFunc("/stream", stream)
http.HandleFunc("/index", index)
err := http.ListenAndServe("127.0.0.1:8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
<?php
// disable nginx buffer
header('X-Accel-Buffering: no');
header('Content-type: text/html; charset=utf-8');
//turn off output buffering
ob_end_flush();
function output($val) {
echo $val;
flush();
// ob_flush();
sleep(1);
}
//必须有3个字符以上,js才开始获取到
output("(counting to 3), Begin:");
for($i = 0 ; $i < 3; $i++) {
output($i+1);
}
output('End.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment