nginx fastcgi如何支持SSE

Posted 27 months ago fastcgi php go nginx sse websocket

SSE 一个代替websocket的轻量级方案

js 这么调用


const source = new EventSource('http://localhost/xxx');

nginx 这么配置


server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # Everything is a 404
        location / {
                fastcgi_pass 127.0.0.1:9090;
                proxy_buffering off;
                fastcgi_buffering off;
proxy_cache off;
proxy_set_header Host $host;

proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
                include fastcgi_params;
        }

        # You may need this to prevent return 404 recursion.
        location = /404.html {
                internal;
        }
}

go

package main

import (
	"fmt"
	"net"
	"net/http"
	"net/http/fcgi"
	_ "net/http/pprof"
	"time"
)

func main() {
	server := http.DefaultServeMux
	listen, err := net.Listen("tcp", "127.0.0.1:9090")
	if err != nil {
		fmt.Printf("listen failed, err:%v\n", err)
		return
	}
	server.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		a := r.URL.Query().Get("aaa")
		w.Write([]byte("aa->" + a))
	})
	server.HandleFunc("/bb", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		f, ok := w.(http.Flusher)
		fmt.Println(ok)
		f.Flush()

		for i := 0; i < 10; i++ {
			w.Write([]byte("event: slide\n"))
			w.Write([]byte("data: aaa\n"))
			w.Write([]byte("retry: 20000\n"))
			w.Write([]byte("\n\n"))
			f.Flush()
			time.Sleep(time.Second * 2)

		}

	})
	go func() {
		http.ListenAndServe(":9876", nil)
	}()
	fcgi.Serve(listen, server)
}

点击评论