63dcfdd5293d9272986c50ff04595218
go 构建 websocket 长连接(1):upgrade、注册 client

我们使用golang构建websocket,支持高性能、高并发,websocket不用多介绍,go自带原生websocketapi,但有些断线重连、信息发送处理不太完善,我们改造gorilla/websocket 用于我们的系统,源码在文章末尾,以下是两个扩展的对比信息。

Gorilla WebSocket compared with other packages

github.com/gorilla golang.org/x/net
RFC 6455 Features
Passes Autobahn Test SuiteYesNo
Receive fragmented messageYesNo, see note 1
Send close messageYesNo
Send pings and receive pongsYesNo
Get the type of a received data messageYesYes, see note 2
Other Features
Compression ExtensionsExperimentalNo
Read message using io.ReaderYesNo, see note 3
Write message using io.WriteCloserYesNo, see note 3

注册client

首先我们定义client相关的struct 用于注册进我们的服务,其中注册和反注册 我们使用channel构造

type Client struct {
    hub *GatewayInfo
    // The websocket connection.
    conn *websocket.Conn
    // Buffered channel of outbound messages.
    send chan []byte
    Id string
    Num int
    Info ClientInfo
}
type GatewayInfo struct {
    // Registered clients.
    clients sync.Map
    // Register requests from the clients.
    register chan *Client
    // Unregister requests from clients.
    unregister chan *Client
}

启动服务 http升级为ws

```
// serveWs handles websocket requests from the peer.
func ServeWs(hub *GatewayInfo, w http.ResponseWriter, r *http.Request) {
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return

top Created with Sketch.