gpt4 book ai didi

go - 如果异常断开,Websocket 会卡住

转载 作者:数据小太阳 更新时间:2023-10-29 03:04:23 24 4
gpt4 key购买 nike

我创建了一个简单的 websocket 来发布 JSON 流。我大部分时间都工作正常,除了少数情况,我认为在循环遍历客户端向它们发送消息时,它卡在异常断开连接的客户端上。我可以在此代码中添加什么措施来缓解它?

Client.go

import (
"github.com/gorilla/websocket"
)

type client struct {
socket *websocket.Conn

send chan *Message
}

func (c *client) read() {
defer c.socket.Close()
for {
_, _, err := c.socket.ReadMessage()
if err != nil {
log.Info("Websocket: %s", err)
break
}
}
}

func (c *client) write() {
defer c.socket.Close()
for msg := range c.send {
err := c.socket.WriteJSON(msg)
if err != nil {
break
}
}
}

Stream.go

import (
"net/http"

"github.com/gorilla/websocket"
)

const (
socketBufferSize = 1024
messageBufferSize = 256
)

var upgrader = &websocket.Upgrader{
ReadBufferSize: socketBufferSize,
WriteBufferSize: socketBufferSize,
}

type Stream struct {
Send chan *Message

join chan *client

leave chan *client

clients map[*client]bool
}

func (s *Stream) Run() {
for {
select {
case client := <-s.join: // joining
s.clients[client] = true
case client := <-s.leave: // leaving
delete(s.clients, client)
close(client.send)
case msg := <-s.Send: // send message to all clients
for client := range s.clients {
client.send <- msg
}
}
}
}

func (s *Stream) ServeHTTP(w http.ResponseWriter, res *http.Request) {
socket, err := upgrader.Upgrade(w, res, nil)
if err != nil {
log.Error(err)
return
}

defer func() {
socket.Close()
}()

client := &client{
socket: socket,
send: make(chan *Message, messageBufferSize),
}

s.join <- client
defer func() { s.leave <- client }()

go client.write()
client.read()
}

最佳答案

参见 Gorilla Chat Application有关如何避免在客户端上阻塞的示例。

关键部分是:

关于go - 如果异常断开,Websocket 会卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45158754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com