Golang轻量级WebSocket库推荐:nhooyr.io/websocket

Golang轻量级WebSocket库推荐:nhooyr.io/websocket GitHub头像

nhooyr/websocket

适用于Go的简约惯用WebSocket库。通过在GitHub上创建账户来为nhooyr/websocket开发做贡献。

README.md文件包含详细的示例,解释了我开发这个库的原因以及它相对于现有实现的改进之处。

如有任何问题,请随时告知。

1 回复

更多关于Golang轻量级WebSocket库推荐:nhooyr.io/websocket的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


nhooyr.io/websocket 是一个优秀的Go语言WebSocket库,它提供了简洁的API和良好的性能。以下是基本使用示例:

服务端代码:

package main

import (
    "context"
    "log"
    "net/http"

    "nhooyr.io/websocket"
    "nhooyr.io/websocket/wsjson"
)

func main() {
    http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
        c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
            InsecureSkipVerify: true, // 生产环境应配置正确的origin检查
        })
        if err != nil {
            log.Printf("websocket accept failed: %v", err)
            return
        }
        defer c.Close(websocket.StatusInternalError, "connection closed")

        ctx := context.Background()
        
        for {
            var v interface{}
            err = wsjson.Read(ctx, c, &v)
            if err != nil {
                log.Printf("read failed: %v", err)
                break
            }
            
            log.Printf("received: %v", v)
            
            err = wsjson.Write(ctx, c, map[string]string{"response": "message received"})
            if err != nil {
                log.Printf("write failed: %v", err)
                break
            }
        }
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

客户端代码:

package main

import (
    "context"
    "log"
    "time"

    "nhooyr.io/websocket"
    "nhooyr.io/websocket/wsjson"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()

    c, _, err := websocket.Dial(ctx, "ws://localhost:8080/ws", nil)
    if err != nil {
        log.Fatal("dial failed:", err)
    }
    defer c.Close(websocket.StatusInternalError, "connection closed")

    // 发送消息
    err = wsjson.Write(ctx, c, map[string]string{"message": "hello"})
    if err != nil {
        log.Fatal("write failed:", err)
    }

    // 接收响应
    var v interface{}
    err = wsjson.Read(ctx, c, &v)
    if err != nil {
        log.Fatal("read failed:", err)
    }
    log.Printf("received: %v", v)

    c.Close(websocket.StatusNormalClosure, "")
}

广播示例:

type client struct {
    conn *websocket.Conn
    send chan []byte
}

type hub struct {
    clients map[*client]bool
    broadcast chan []byte
    register chan *client
    unregister chan *client
}

func (h *hub) run() {
    for {
        select {
        case client := <-h.register:
            h.clients[client] = true
        case client := <-h.unregister:
            if _, ok := h.clients[client]; ok {
                delete(h.clients, client)
                close(client.send)
            }
        case message := <-h.broadcast:
            for client := range h.clients {
                select {
                case client.send <- message:
                default:
                    close(client.send)
                    delete(h.clients, client)
                }
            }
        }
    }
}

这个库的主要优势包括符合Go语言习惯的API设计、良好的性能表现、完整的RFC 6455实现支持,以及简洁的代码结构。相比其他WebSocket实现,nhooyr.io/websocket在内存使用和连接处理方面表现更优。

回到顶部