Skip to content

Misaka-10233/ws

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ws

A simple WebSocket client and server implementation in Go.

一个简单的 Go WebSocket 客户端和服务器实现。

Features / 特性

  • Client / 客户端

    • Automatic reconnection with exponential backoff / 自动重连,支持指数退避
    • Heartbeat mechanism / 心跳机制
    • Concurrent-safe / 并发安全
    • Context-based lifecycle management / 基于上下文的生命周期管理
  • Server / 服务器

    • Support multiple concurrent connections / 支持多并发连接
    • Heartbeat mechanism per connection / 每个连接的心跳机制
    • Broadcast to all connections / 广播到所有连接
    • Health check endpoint / 健康检查端点

Installation / 安装

go get github.com/Misaka-10233/ws

Quick Start / 快速开始

Client / 客户端

package main

import (
    "context"
    "log"
    "time"

    "github.com/Misaka-10233/ws"
    "github.com/coder/websocket"
)

func main() {
    ctx := context.Background()

    // Create callback functions / 创建回调函数
    callback := ws.CallBack{
        OnConnect: func(conn *websocket.Conn) {
            log.Println("Connected to server / 已连接到服务器")
        },
        OnDisconnect: func(conn *websocket.Conn) {
            log.Println("Disconnected from server / 与服务器断开连接")
        },
    }

    // Create WebSocket client / 创建 WebSocket 客户端
    client := ws.NewWsClient("ws://localhost:8080/ws", ctx, callback,
        ws.ClientWithHeartbeatInterval(5*time.Second),  // Heartbeat interval / 心跳间隔
        ws.ClientWithWriteTimeout(1*time.Second),       // Write timeout / 写入超时
    )

    // Get message channel / 获取消息通道
    msgChan := ws.GetClientMsgChan(client)

    // Read messages / 读取消息
    go func() {
        for msg := range msgChan {
            log.Printf("Received from %s: %s / 收到来自 %s 的消息: %s", 
                msg.Addr, string(msg.Data), msg.Addr, string(msg.Data))
        }
    }()

    // Write message / 发送消息
    client.Write(websocket.MessageText, []byte("Hello Server / 你好服务器"))

    // Keep running / 保持运行
    time.Sleep(30 * time.Second)

    // Close client / 关闭客户端
    client.Close()
}

Server / 服务器

package main

import (
    "context"
    "log"
    "time"

    "github.com/Misaka-10233/ws"
    "github.com/coder/websocket"
)

func main() {
    ctx := context.Background()

    // Create callback functions / 创建回调函数
    callback := ws.CallBack{
        OnConnect: func(conn *websocket.Conn) {
            log.Println("Client connected / 客户端已连接")
        },
        OnDisconnect: func(conn *websocket.Conn) {
            log.Println("Client disconnected / 客户端已断开连接")
        },
    }

    // Create WebSocket server / 创建 WebSocket 服务器
    server := ws.NewWsServer(":8080", ctx, callback,
        ws.ServerWithHeartbeatInterval(5*time.Second),  // Heartbeat interval / 心跳间隔
        ws.ServerWithWriteTimeout(1*time.Second),       // Write timeout / 写入超时
        ws.ServerWithMsgChanSize(100),                  // Message channel size / 消息通道大小
    )

    // Get message channel / 获取消息通道
    msgChan := server.GetMsgChan()

    // Read messages / 读取消息
    go func() {
        for msg := range msgChan {
            log.Printf("Received from %s: %s / 收到来自 %s 的消息: %s", 
                msg.Addr, string(msg.Data), msg.Addr, string(msg.Data))
        }
    }()

    // Run server / 运行服务器
    opts := &websocket.AcceptOptions{
        // Configure CORS or other options / 配置 CORS 或其他选项
    }
    
    log.Println("Server starting... / 服务器启动中...")
    if err := server.Run(opts); err != nil {
        log.Fatal("Server error / 服务器错误:", err)
    }
}

API Reference / API 参考

Types / 类型

Resp - Message Response / 消息响应

type Resp struct {
    Addr string                   // Client address / 客户端地址
    Type websocket.MessageType    // Message type (Text/Binary) / 消息类型(文本/二进制)
    Data []byte                   // Message data / 消息数据
}

Req - Message Request / 消息请求

type Req struct {
    Type websocket.MessageType    // Message type / 消息类型
    Data []byte                   // Message data / 消息数据
}

CallBack - Event Callbacks / 事件回调

type CallBack struct {
    OnConnect    func(*websocket.Conn)    // Called on connection / 连接建立时调用
    OnDisconnect func(*websocket.Conn)    // Called on disconnection / 连接断开时调用
}

State - Connection State / 连接状态

const (
    StateConnected    = iota    // Connected / 已连接
    StateDisconnected           // Disconnected / 已断开
)

Client / 客户端

NewWsClient - Create Client / 创建客户端

func NewWsClient(url string, parent context.Context, callBack CallBack, options ...func(*WsClient)) *WsClient

Creates a new WebSocket client with automatic reconnection. / 创建支持自动重连的 WebSocket 客户端。

GetClientMsgChan - Get Message Channel / 获取消息通道

func GetClientMsgChan(wsc *WsClient) chan Resp

Returns the channel for receiving messages. / 返回用于接收消息的通道。

(*WsClient) Write - Send Message / 发送消息

func (wsc *WsClient) Write(msgType websocket.MessageType, msg []byte)

Sends a message to the server. / 向服务器发送消息。

(*WsClient) GetClientState - Get Connection State / 获取连接状态

func (wsc *WsClient) GetClientState() State

Returns the current connection state. / 返回当前连接状态。

(*WsClient) Close - Close Client / 关闭客户端

func (wsc *WsClient) Close()

Closes the client and releases resources. / 关闭客户端并释放资源。

Server / 服务器

NewWsServer - Create Server / 创建服务器

func NewWsServer(url string, parent context.Context, callBack CallBack, opts ...func(*WsServer)) *WsServer

Creates a new WebSocket server. / 创建新的 WebSocket 服务器。

(*WsServer) Run - Run Server / 运行服务器

func (wss *WsServer) Run(opts *websocket.AcceptOptions) error

Starts the server and blocks until shutdown. / 启动服务器并阻塞直到关闭。

(*WsServer) GetMsgChan - Get Message Channel / 获取消息通道

func (wss *WsServer) GetMsgChan() chan Resp

Returns the channel for receiving messages from all clients. / 返回用于接收所有客户端消息的通道。

(*WsServer) GetAllConnections - Get All Connections / 获取所有连接

func (wss *WsServer) GetAllConnections() []string

Returns addresses of all connected clients. / 返回所有已连接客户端的地址。

(*WsServer) WriteTo - Send to Specific Client / 发送给指定客户端

func (wss *WsServer) WriteTo(addr string, msgType websocket.MessageType, msg []byte)

Sends a message to a specific client. / 向指定客户端发送消息。

(*WsServer) WriteToAll - Broadcast / 广播

func (wss *WsServer) WriteToAll(msgType websocket.MessageType, msg []byte)

Sends a message to all connected clients. / 向所有已连接客户端发送消息。

Client Options / 客户端选项

Option / 选项 Description / 描述 Default / 默认值
ClientWithHeartbeatInterval(d) Heartbeat interval / 心跳间隔 5s
ClientWithHeartbeatTimeout(d) Heartbeat timeout / 心跳超时 1s
ClientWithWriteTimeout(d) Write timeout / 写入超时 1s
ClientWithReadTimeout(d) Read timeout / 读取超时 1s
ClientWithWriteQueSize(n) Write queue size / 写入队列大小 16
ClientWithMsgChanSize(n) Message channel size / 消息通道大小 16

Server Options / 服务器选项

Option / 选项 Description / 描述 Default / 默认值
ServerWithHeartbeatInterval(d) Heartbeat interval / 心跳间隔 5s
ServerWithHeartbeatTimeout(d) Heartbeat timeout / 心跳超时 1s
ServerWithWriteTimeout(d) Write timeout / 写入超时 1s
ServerWithWriteQueSize(n) Write queue size / 写入队列大小 16
ServerWithMsgChanSize(n) Message channel size / 消息通道大小 16

Endpoints / 端点

When running the server, the following endpoints are available: / 运行服务器时,以下端点可用:

  • /ws - WebSocket endpoint / WebSocket 端点
  • /health - Health check endpoint (returns HTTP 200) / 健康检查端点(返回 HTTP 200)

License / 许可证

MIT License

About

A simple WebSocket client and Server Implementation.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages