summaryrefslogtreecommitdiffstats
path: root/dom/base/test/delayedServerEvents.sjs
blob: cfc1bca508f9542e8d26825f0299fd2fec92eb07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// this will take strings_to_send.length*500 ms = 5 sec

var timer = null;
var strings_to_send = [
  "retry:999999999\ndata\r\n\nda",
  "ta",
  ":",
  "de",
  "layed1\n\n",
  "",
  "",
  "data:delayed2\n\n",
  "",
  "",
];
var resp = null;

function sendNextString() {
  if (!strings_to_send.length) {
    timer.cancel();
    resp.finish();
    timer = null;
    resp = null;
    return;
  }

  try {
    resp.write(strings_to_send.shift());
  } catch (e) {
    timer.cancel();
    timer = null;
    resp = null;
  }
}

function handleRequest(request, response) {
  var bytes = strings_to_send.reduce((len, s) => len + s.length, 0);

  response.seizePower();
  response.write("HTTP/1.1 200 OK\r\n");
  response.write(`Content-Length: ${bytes}\r\n`);
  response.write("Content-Type: text/event-stream; charset=utf-8\r\n");
  response.write("Cache-Control: no-cache, must-revalidate\r\n");
  response.write("\r\n");

  resp = response;

  timer = Components.classes["@mozilla.org/timer;1"].createInstance(
    Components.interfaces.nsITimer
  );
  timer.initWithCallback(
    sendNextString,
    500,
    Components.interfaces.nsITimer.TYPE_REPEATING_SLACK
  );
}