代码之家  ›  专栏  ›  技术社区  ›  Escher

如何在HTTP处理程序函数返回后保持WebSocket连接打开?

  •  3
  • Escher  · 技术社区  · 7 年前

    目前,我有一个dataStream结构图,如下所示:

    struct dataStream {
      data chan byte[]
      conns []*websocket.Connection
    }
    

    下面是将请求升级到WebSocket,然后尝试将WebSocket连接添加到dataStreams conns的伪代码:

    func process_request(w http.ResponseWriter, r *http.Request) {
      // hundred lines of business logic...
      c := upgrade websocket connection
      defer c.Close()
      if dataStream exists {
        append the new connection c to the dataStream.conns slice
      } else {
        create new dataStream
        append the new connection c to the dataStream.conns slice
        stream(dataStream)
      }
    }
    

    接下来是 stream 上述代码块中提到的函数。其中一个在后台为每个数据流运行(不是为每个WebSocket连接运行)。

    func stream(ds *dataStream) {
      ticker := time.NewTicker(poll every ~10 seconds)
      go func() { // this is to poll and remove closed connections
      for _ = range ticker.C {
        for traverse ds.conns {
          ping all connections, remove any closed ones and free memory
          if len(ds.conns == 0){ // no more connections are listening to this dataStream
            delete the ds dataStream and free the memory
            stop ticker
            return // kill goroutine and free the memory
          }
        }
      }}()
      while len(ds.conns) != 0 { // while there are open connections
        fetch any available <-ds.data from channel
        write the data as websocket message to each connection
      }
    }
    

    process_request 一旦水流到达底部 if statement 在新连接附加到 dataStream.conns 正在关闭WebSocket连接! stream() 正在后台运行,并轮询已将关闭的连接添加到 ds.conns 切片并移除。

    因此我的问题是:

    我应该采取什么方法来保持WebSocket连接在 处理\u请求 处理函数返回,优先不为每个连接运行单独的goroutine?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Cerise Limón    7 年前

    应用程序必须显式关闭Gorilla连接。当HTTP处理程序函数返回时,连接不会自动关闭。