如何为服务器发送事件(SSE、EventStream)配置 IIS 的 HTTPPlatformHandler

How to config HTTPPlatformHandler of IIS for Server Sent Event (SSE, EventStream)

目前我有提供 SSE 作为服务的程序,我必须在 IIS 上部署。但它不能正常工作, 这是我 运行 .exe 没有 IIS 时的结果。

data: Hello, world

但是当它 运行 落后于 IIS 时,浏览器卡在加载中。 我必须刷新事件 Hello, world 千次以使 IIS 刷新结果到浏览器并且它立即刷新而不是像 SSE 那样使​​用增量更新。

这是我的 web.config

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <handlers>
          <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
        </handlers>
        <httpPlatform processPath=".\sse_server.exe" 
          arguments="-port=%HTTP_PLATFORM_PORT% -environment development" 
          stdoutLogEnabled="false" 
          requestTimeout="00:05:00" 
          stdoutLogFile=".\sse_server_log">
        </httpPlatform>
        <urlCompression doStaticCompression="true" doDynamicCompression="false" />
        <caching enabled="false" enableKernelCache="false" />
      </system.webServer>
    </configuration>

这是我的 go 代码

func SSEHello(rw http.ResponseWriter, flusher http.Flusher) {
    rw.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
    rw.Header().Set("Cache-Control", "no-cache")
    rw.Header().Set("Connection", "keep-alive")
    rw.WriteHeader(http.StatusOK)
    for i := 0; i < 1000; i++ {
        rw.Write([]byte("data:Hello, world\n\n"))
        flusher.Flush()
        time.Sleep(time.Millisecond * 100)
    }
}

其实HttpPlatformHandler有8kb output buffer,所以我的消息并没有立即发出。

我要改HttpPlatformHandler to ASP.NET Core Module, 所以 web.config 必须更新到这个。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.webServer>
        <handlers>
          <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
        </handlers>
        <aspNetCore processPath=".\sse_server.exe"  />
      </system.webServer>
    </configuration>

要在 iis 上以 aspNetCore 身份启动 go 的应用程序,应用程序需要获取环境变量名称 ASPNETCORE_PORT,然后在该端口上启动 http 服务。

port := os.Getenv("ASPNETCORE_PORT")
http.ListenAndServe(":"+port, nil)

就这些了!