Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - Cloudflare Workers - SSE

Is there a way to do server-side-events with cloudflare workers? I've only found one way but it'll stop right after returning the response.

    const { readable, writable } = new TransformStream();
    const response = {
      headers: new Headers({
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        Connection: 'keep-alive',
      }),
      status: 101
    };

    setInterval(() => {
      const encoder = new TextEncoder();
      const writer = writable.getWriter();
      writer.write(encoder.encode(`data: hello

`));
    }, 5000);

    return new Response(readable, response);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two problems with your example code:

  • You should not set status code 101. Status code 101 means "switching protocols", i.e. the server is going to begin speaking something other than HTTP. This is used, for example, with WebSockets. But, your example code doesn't use a different protocol -- it's just regular HTTP with a streaming response body. The Workers runtime does not support switching protocols except to WebSocket, so it will refuse to serve your 101 status code, and will instead serve an error to the client.
  • You are calling getWriter() on every interval, but you can only have one Writer, so on intervals after the first, the call fails. You should instead call getWriter() once before setting the interval, then reuse that writer.

Both of these problems show up as errors in the JavaScript console when running your code in the preview (e.g. on cloudflareworkers.com, or in the Cloudflare dashboard, or using wrangler preview or wrangler dev). I recommend using the preview to debug your code, as it can tell you about errors that are invisible to the client.

The following code works for me in the preview -- text gets added to the response every 5 seconds as expected:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const { readable, writable } = new TransformStream();
  const encoder = new TextEncoder();
  const writer = writable.getWriter();
  setInterval(() => {
    writer.write(encoder.encode(`data: hello

`));
  }, 5000);

  return new Response(readable);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...