zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[go] 解决:concurrent write to websocket connection

2023-02-18 15:41:30 时间

出现这个问题是因为并发的调用了github.com/gorilla/websocket库的WriteMessage方法

在websocket连接上有多个groutinue同时调用写方法

 

go官方的解释:

websocket · pkg.go.dev

 

 

并发 
连接支持一个并发读取器和一个并发写入器。

应用程序负责确保不超过一个 goroutine 同时调用写入方法(NextWriter、SetWriteDeadline、WriteMessage、WriteJSON、EnableWriteCompression、SetCompressionLevel),并且不超过一个 goroutine 调用读取方法(NextReader、SetReadDeadline、ReadMessage、ReadJSON、SetPongHandler) , SetPingHandler) 并发。

Close 和 WriteControl 方法可以与所有其他方法可以并发调用。

 

每一个请求都是一个groutine,如果有多个groutine同时请求并且要写回数据,就会出现这个错误

 

一定要加上锁,并且在业务上避免多个同时调用

 

我遇到的问题是,我有两个结构体,但是conn是同一个,虽然每一个在调用时加了锁,只是锁定不同的结构体,所以User和Message同时调用还是有并发问题

type User struct {
    Conn       *websocket.Conn
    Name       string
    Id         string
    Avator     string
    To_id      string
    Ent_id     string
    Role_id    string
    Mux        sync.Mutex
    UpdateTime time.Time
}
type Message struct {
    conn        *websocket.Conn
    context     *gin.Context
    content     []byte
    messageType int
    Mux         sync.Mutex
}