目前,我有一个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?