登录
首页 >  Golang >  Go问答

并发写入 websocket 连接

来源:stackoverflow

时间:2024-04-17 15:15:31 395浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《并发写入 websocket 连接》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我正在使用 github.com/gorilla/websocket 作为 websockets。我有这个代码

type conn struct {
    conn *websocket.conn
    username string
    hand []string
    mu *sync.mutex
}
func (c *conn) send(messagetype int, message []byte) error {
    c.mu.lock()
    defer c.mu.unlock()
    return c.conn.writemessage(messagetype, message)
}
//later...
connection.send(messagetype, []byte("play"))
connection.send(messagetype, []byte("[\"a\", \"b\", \"c\"]"))

最后两行给了我错误。如果您需要更多代码来解决这个问题,请告诉我。错误如下:

2019/06/15 15:19:03 http: panic serving [::1]:56788: concurrent write to websocket connection
goroutine 10 [running]:
net/http.(*conn).serve.func1(0xc000164140)
    /usr/lib64/go/1.11/src/net/http/server.go:1746 +0xd0
panic(0x6654e0, 0x7125a0)
    /usr/lib64/go/1.11/src/runtime/panic.go:513 +0x1b9
github.com/gorilla/websocket.(*messageWriter).flushFrame(0xc000043a18, 0xc000016501, 0xc00001656c, 0x0, 0x4, 0x713e00, 0xc0001141e0)
    /home/victor/programs/goprograms/src/github.com/gorilla/websocket/conn.go:597 +0x631
github.com/gorilla/websocket.(*Conn).WriteMessage(0xc0001a4160, 0x1, 0xc000016568, 0x4, 0x8, 0x4, 0xc000016568)
    /home/victor/programs/goprograms/src/github.com/gorilla/websocket/conn.go:753 +0x24b
main.(*CONN).Send(0xc00015c280, 0x1, 0xc000016568, 0x4, 0x8, 0x0, 0x0)
    /home/victor/programs/goprograms/src/v/asdf/network/main.go:32 +0x9e
main.wsHandler(0x716960, 0xc00011e380, 0xc000116400)
    /home/victor/programs/goprograms/src/v/asdf/network/main.go:68 +0x501
net/http.HandlerFunc.ServeHTTP(0x6e1ab0, 0x716960, 0xc00011e380, 0xc000116400)
    /usr/lib64/go/1.11/src/net/http/server.go:1964 +0x44
net/http.(*ServeMux).ServeHTTP(0x8dadc0, 0x716960, 0xc00011e380, 0xc000116400)
    /usr/lib64/go/1.11/src/net/http/server.go:2361 +0x127
net/http.serverHandler.ServeHTTP(0xc00008d040, 0x716960, 0xc00011e380, 0xc000116400)
    /usr/lib64/go/1.11/src/net/http/server.go:2741 +0xab
net/http.(*conn).serve(0xc000164140, 0x716b60, 0xc00005a800)
    /usr/lib64/go/1.11/src/net/http/server.go:1847 +0x646
created by net/http.(*Server).Serve
    /usr/lib64/go/1.11/src/net/http/server.go:2851 +0x2f5

这是我正在使用的完整代码 - 第 75 行是设置连接的位置。我不明白地图中的一项下怎么可能有多个连接。


解决方案


您的 func wsHandler(w http.ResponseWriter, r *http.Request) 未通过全局变量映射 connections 正确同步

wsHandler 的每次调用都是在单独的 goroutine 中进行的:

来自https://golang.org/pkg/net/http/#Server.ListenAndServe

来自https://golang.org/pkg/net/http/#Server.Serve

今天关于《并发写入 websocket 连接》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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