websocket

package
v0.1.26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2025 License: MIT Imports: 10 Imported by: 0

README

Mist WebSocket模块

Mist WebSocket模块提供了在Mist框架中轻松集成WebSocket功能的能力,支持实时通信应用如聊天、通知和游戏。

主要特性

  • 基于gorilla/websocket构建的高性能WebSocket实现
  • 优雅的连接管理和自动清理机制
  • 内置心跳检测和保活机制
  • 支持房间/频道系统,便于构建分组通信
  • 丰富的广播API支持不同的消息发送模式
  • 通过Hub实现中心化消息处理
  • 完整的错误处理和超时控制
  • 丰富的示例代码,包括聊天室和通知系统

快速开始

1. 基本用法:创建Echo服务器
package main

import (
    "github.com/dormoron/mist"
    "github.com/dormoron/mist/websocket"
)

func main() {
    server := mist.InitHTTPServer()
    
    // 创建一个简单的Echo WebSocket处理程序
    server.GET("/ws/echo", websocket.WebSocket(nil, func(conn *websocket.Connection) {
        // 持续接收消息
        for {
            msg, err := conn.Receive()
            if err != nil {
                // 连接已关闭或出错
                return
            }
            
            // 简单地将消息回显给发送者
            if err := conn.Send(msg.Type, msg.Data); err != nil {
                return
            }
        }
    }))
    
    server.Start(":8080")
}
2. 高级用法:创建聊天室
package main

import (
    "encoding/json"
    "time"
    
    "github.com/dormoron/mist"
    "github.com/dormoron/mist/websocket"
    "github.com/google/uuid"
)

func main() {
    server := mist.InitHTTPServer()
    
    // 创建WebSocket Hub管理连接和房间
    hub := websocket.NewHub()
    
    // 注册WebSocket路由
    server.GET("/ws/chat", websocket.WebSocket(nil, func(conn *websocket.Connection) {
        // 为连接生成唯一ID
        connID := uuid.New().String()
        
        // 注册连接到Hub
        hub.Register(connID, conn)
        
        // 持续处理消息...
        // 查看完整示例请参考examples.go中的ExampleChatServer函数
    }))
    
    server.Start(":8080")
}

核心组件

Connection

表示单个WebSocket连接,提供消息发送和接收功能。

// 发送文本消息
conn.SendText("Hello!")

// 发送二进制数据
conn.SendBinary([]byte{1, 2, 3})

// 接收消息
msg, err := conn.Receive()
Hub

管理多个WebSocket连接,支持房间和广播功能。

// 将连接注册到Hub
hub.Register(userID, conn)

// 将连接加入房间
hub.JoinRoom("chat", userID)

// 向房间广播消息
hub.BroadcastTextToRoom("chat", "有人加入了聊天室")

// 向所有连接广播消息
hub.BroadcastText("服务器维护通知")
WebSocket助手函数

创建WebSocket处理函数,简化HTTP到WebSocket的升级过程。

server.GET("/ws", websocket.WebSocket(config, func(conn *websocket.Connection) {
    // 处理WebSocket连接...
}))

配置选项

通过Config结构体自定义WebSocket行为:

config := websocket.DefaultConfig()
config.WriteBufferSize = 8192
config.ReadBufferSize = 8192
config.MaxMessageSize = 1024 * 1024 // 1MB
config.PingInterval = 10 * time.Second

安全性考虑

  • 默认配置已启用Origin检查,但在生产环境中应自定义CheckOrigin函数
  • 建议使用TLS (wss://)保护WebSocket通信
  • 对消息大小设置合理的限制(MaxMessageSize)以防止DoS攻击
  • 实现认证机制验证连接请求

性能优化

  • 连接池使用map实现,支持快速查找
  • 读写操作采用goroutine隔离,避免阻塞
  • 内置消息缓冲区,防止慢客户端影响性能
  • 自动关闭不活跃的连接,避免资源泄漏

客户端兼容性

Mist WebSocket实现兼容所有支持WebSocket协议(RFC 6455)的客户端,包括:

  • 现代浏览器(Chrome, Firefox, Safari, Edge)
  • JavaScript客户端库(socket.io, WebSocket API)
  • 移动应用WebSocket客户端
  • 各种语言的WebSocket客户端库

完整示例

参见examples.go文件中的完整聊天室和通知系统示例。

Documentation

Index

Constants

View Source
const (
	// TextMessage 表示文本消息
	TextMessage = MessageType(websocket.TextMessage)

	// BinaryMessage 表示二进制消息
	BinaryMessage = MessageType(websocket.BinaryMessage)

	// CloseMessage 表示关闭连接
	CloseMessage = MessageType(websocket.CloseMessage)

	// PingMessage 表示Ping消息
	PingMessage = MessageType(websocket.PingMessage)

	// PongMessage 表示Pong消息
	PongMessage = MessageType(websocket.PongMessage)
)

Variables

View Source
var (
	// ErrConnectionClosed 表示WebSocket连接已关闭
	ErrConnectionClosed = errors.New("websocket: 连接已关闭")

	// ErrMessageTooLarge 表示消息大小超过限制
	ErrMessageTooLarge = errors.New("websocket: 消息太大")

	// ErrInvalidMessageType 表示消息类型无效
	ErrInvalidMessageType = errors.New("websocket: 消息类型无效")

	// ErrChannelFull 表示发送通道已满
	ErrChannelFull = errors.New("websocket: 发送通道已满")

	// ErrChannelClosed 表示通道已关闭
	ErrChannelClosed = errors.New("websocket: 通道已关闭")
)

Functions

func ExampleChatServer

func ExampleChatServer() *mist.HTTPServer

示例2:创建聊天室服务器

func ExampleEchoServer

func ExampleEchoServer() mist.HandleFunc

示例1:创建简单的Echo服务器

func ExampleNotificationService

func ExampleNotificationService() *mist.HTTPServer

ExampleNotificationService 是一个实时通知服务示例

func WebSocket

func WebSocket(config *Config, handler func(*Connection)) mist.HandleFunc

WebSocket 创建一个升级HTTP连接到WebSocket连接的处理函数

Types

type ChatMessage

type ChatMessage struct {
	// 消息类型
	Type string `json:"type"`

	// 发送者ID
	Sender string `json:"sender"`

	// 目标房间
	Room string `json:"room,omitempty"`

	// 消息内容
	Content string `json:"content"`

	// 发送时间
	Timestamp int64 `json:"timestamp"`
}

ChatMessage 表示聊天消息结构

type Config

type Config struct {
	// WriteBufferSize 是写缓冲区大小
	WriteBufferSize int

	// ReadBufferSize 是读缓冲区大小
	ReadBufferSize int

	// MaxMessageSize 是最大消息大小
	MaxMessageSize int64

	// HandshakeTimeout 是握手超时时间
	HandshakeTimeout time.Duration

	// ReadTimeout 是读取超时时间
	ReadTimeout time.Duration

	// WriteTimeout 是写入超时时间
	WriteTimeout time.Duration

	// PingInterval 是Ping间隔时间
	PingInterval time.Duration

	// MessageBufferSize 是消息缓冲区大小
	MessageBufferSize int

	// CheckOrigin 是检查Origin的函数
	CheckOrigin func(r *http.Request) bool
}

Config 表示WebSocket配置

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 返回默认配置

type Connection

type Connection struct {
	// contains filtered or unexported fields
}

Connection 表示WebSocket连接

func (*Connection) Close

func (c *Connection) Close() error

Close 关闭连接

func (*Connection) Context

func (c *Connection) Context() context.Context

Context 返回连接的上下文

func (*Connection) GetUserValue

func (c *Connection) GetUserValue(key string) (interface{}, bool)

GetUserValue 获取用户值

func (*Connection) IsConnected

func (c *Connection) IsConnected() bool

IsConnected 返回连接是否仍然活跃

func (*Connection) Receive

func (c *Connection) Receive() (Message, error)

Receive 接收消息

func (*Connection) Send

func (c *Connection) Send(messageType MessageType, data []byte) error

Send 发送消息

func (*Connection) SendBinary

func (c *Connection) SendBinary(data []byte) error

SendBinary 发送二进制消息

func (*Connection) SendText

func (c *Connection) SendText(text string) error

SendText 发送文本消息

func (*Connection) SetUserValue

func (c *Connection) SetUserValue(key string, value interface{})

SetUserValue 设置用户值

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub 管理所有活跃的WebSocket连接和消息广播

func NewHub

func NewHub() *Hub

NewHub 创建新的Hub实例

func (*Hub) BroadcastBinary

func (h *Hub) BroadcastBinary(data []byte) int

BroadcastBinary 向所有连接广播二进制消息

func (*Hub) BroadcastBinaryToRoom

func (h *Hub) BroadcastBinaryToRoom(roomName string, data []byte) int

BroadcastBinaryToRoom 向房间内的所有连接广播二进制消息

func (*Hub) BroadcastText

func (h *Hub) BroadcastText(text string) int

BroadcastText 向所有连接广播文本消息

func (*Hub) BroadcastTextToRoom

func (h *Hub) BroadcastTextToRoom(roomName string, text string) int

BroadcastTextToRoom 向房间内的所有连接广播文本消息

func (*Hub) BroadcastToAll

func (h *Hub) BroadcastToAll(msgType MessageType, data []byte) int

BroadcastToAll 向所有连接广播消息

func (*Hub) BroadcastToRoom

func (h *Hub) BroadcastToRoom(roomName string, msgType MessageType, data []byte) int

BroadcastToRoom 向房间内的所有连接广播消息

func (*Hub) CountConnections

func (h *Hub) CountConnections() int

CountConnections 计算当前活跃连接数

func (*Hub) CountRoomConnections

func (h *Hub) CountRoomConnections(roomName string) int

CountRoomConnections 计算房间内活跃连接数

func (*Hub) GetConnection

func (h *Hub) GetConnection(connID string) (*Connection, bool)

GetConnection 获取指定ID的连接

func (*Hub) GetRoomConnections

func (h *Hub) GetRoomConnections(roomName string) []string

GetRoomConnections 获取房间内所有连接ID

func (*Hub) GetRooms

func (h *Hub) GetRooms() []string

GetRooms 获取所有房间名称

func (*Hub) JoinRoom

func (h *Hub) JoinRoom(roomName string, connID string) bool

JoinRoom 让连接加入一个房间

func (*Hub) LeaveRoom

func (h *Hub) LeaveRoom(roomName string, connID string) bool

LeaveRoom 让连接离开一个房间

func (*Hub) Register

func (h *Hub) Register(connID string, conn *Connection)

Register 注册一个新的WebSocket连接

func (*Hub) Unregister

func (h *Hub) Unregister(connID string)

Unregister 注销一个WebSocket连接

type Message

type Message struct {
	// Type 是消息类型
	Type MessageType

	// Data 是消息数据
	Data []byte
}

Message 表示WebSocket消息

type MessageType

type MessageType int

MessageType 定义WebSocket消息类型

type Upgrader

type Upgrader struct {
	// contains filtered or unexported fields
}

Upgrader 是WebSocket连接升级器

func NewUpgrader

func NewUpgrader(config *Config) *Upgrader

NewUpgrader 创建一个新的WebSocket升级器

func (*Upgrader) Upgrade

func (u *Upgrader) Upgrade(ctx *mist.Context) (*Connection, error)

Upgrade 将HTTP连接升级为WebSocket连接

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL