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

Gorilla WebSocket compared with other packages

RFC 6455 Features
No
Receive fragmented messageYesNo, see note 1
Send close message
Send pings and receive pongsNo
Get the type of a received data messageYesYes, see note 2
Other Features
ExperimentalNo
Read message using io.ReaderNo, see note 3
Write message using io.WriteCloserNo, 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