登录
首页 >  Golang >  Go问答

如何在 HTTP 处理函数返回后保持 WebSocket 连接有效?

来源:stackoverflow

时间:2024-03-26 09:27:36 262浏览 收藏

在 HTTP 处理函数返回后保持 WebSocket 连接有效是一个常见的问题。本文提出了一种解决方案,即在处理函数中删除 `defer` 语句,以防止应用程序自动关闭连接。这样,WebSocket 连接将保持打开状态,即使处理函数已返回。该解决方案有助于避免为每个连接创建单独的 goroutine,从而节省资源,特别是当有大量连接时。

问题内容

我正在尝试编写代码来传输某个主题的数据,例如广播电台(一个广播公司,几个听众)。我被困在如何处理新的 websocket 连接请求,而无需为每个打开的 websocket 提供一个 goroutine(这对于同一“站”的许多“侦听器”来说开始变得资源密集型)。

目前,我有一个 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 语句 的底部,在新连接追加到 datastream.conns 切片之后,函数就会终止关闭 websocket 连接! 结果,stream() 在后台运行,并轮询已将关闭的连接添加到 ds.conns 切片并将其删除。

因此我的问题:

即使在 process_request 处理函数返回后,我应该采取什么方法来保持 websocket 连接打开,最好不要为每个连接运行单独的 goroutine?


解决方案


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

在这种情况下,应用程序使用 defer 语句在从处理程序返回时关闭连接。删除 defer 语句以避免关闭连接。

今天关于《如何在 HTTP 处理函数返回后保持 WebSocket 连接有效?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>