engine

package module
v3.0.0-...-caf1bf9 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 29 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Engine.IO:Go 实时通信引擎

Go Reference Go Report Card

概述

Engine.IO 是 Socket.IO Go 实现基于传输层的跨浏览器、跨设备双向通信层。它屏蔽 WebSocket、Polling、WebTransport 等传输方式的差异,并提供统一 API。

特性

  • 支持多种传输方式(WebSocket、Polling、WebTransport)
  • 自动升级传输方式
  • 带心跳机制的有状态连接
  • 二进制数据支持
  • 跨浏览器兼容
  • 支持 Engine.IO 协议 v3 和 v4
  • 可选 ClusterServer,支持跨监听器读写锁、Polling包转发、关闭和Upgrade接管

安装

go get github.com/aqcool/socket.io/servers/engine/v3

快速开始

package main

import (
    "github.com/aqcool/socket.io/servers/engine/v3"
    "github.com/aqcool/socket.io/servers/engine/v3/config"
    "github.com/aqcool/socket.io/v3/pkg/types"
)

func main() {
    // Configure server options
    serverOptions := &config.ServerOptions{}
    serverOptions.SetAllowEIO3(true)
    serverOptions.SetCors(&types.Cors{
        Origin:      "*",
        Credentials: true,
    })

    // Create and start server
    server := engine.Listen(":4444", serverOptions, nil)

    // Handle connections
    server.On("connection", func(sockets ...any) {
        socket := sockets[0].(engine.Socket)
        socket.On("message", func(args ...any) {
            // Handle messages
        })
    })

    // Keep the server running
    select {}
}

用法

服务端初始化方式
  1. 直接监听
  2. 集成 HTTP 服务端
  3. 自定义请求处理
  4. 集成 WebSocket
  5. WebTransport 支持

配置

服务端选项
opts := &config.ServerOptions{}
opts.SetPingTimeout(20_000 * time.Millisecond)
opts.SetPingInterval(25_000 * time.Millisecond)
opts.SetUpgradeTimeout(10_000 * time.Millisecond)
opts.SetMaxHttpBufferSize(1e6)
opts.SetCookie(&http.Cookie{}) // 默认 io=<sid>; Path=/; HttpOnly; SameSite=Lax
opts.SetCookiePath("")        // 显式省略 Path,等价于官方 cookie.path=false
opts.SetCookieHttpOnly(false) // 显式关闭 HttpOnly
opts.SetGenerateId(func(ctx *types.HttpContext) (string, error) {
    return createSessionID(ctx) // 返回错误会拒绝握手并触发 ID_GENERATION_ERROR
})
// ...

普通服务端可以使用任意满足基础校验的自定义SID。若这个选项交给 ClusterServer,跨Go实例或与Node混部的SID必须是20字符,并满足本项目 utils.IsValidSid 的安全字符集,建议使用base64url。官方Cluster Engine对未知SID只检查长度20;包含特殊符号的20字符SID可能被官方Node路由,但会被Go以400拒绝,这是刻意的安全加严和已知差异。

ClusterServer

ClusterServer 允许同一Engine.IO会话的后续请求到达其他监听器。它会在共享Bus上申请读锁或写锁,并转发Packet、Drain、Close、Upgrade及升级前缓冲,不依赖粘性会话:

bus := engine.NewMemoryClusterBus()
defer bus.Close()

cluster, err := engine.NewClusterServer(bus, opts, &engine.ClusterOptions{
    ResponseTimeout:  time.Second,
    NoopUpgradeInterval: 200 * time.Millisecond,
})
if err != nil {
    log.Fatal(err)
}
defer cluster.Close()

cluster.On("cluster_error", func(values ...any) {
    log.Printf("cluster error: %v", values[0])
})
log.Fatal(http.ListenAndServe(":4444", cluster))

每个监听器都需要自己的 ClusterServer 订阅。MemoryClusterBus 可以由同一进程内的多个监听器共享,但不能跨进程;它按订阅者异步交付,对有序 Publish 调用保持FIFO,且不会从 Publish 调用栈同步重入listener。自定义 ClusterBus 必须同样响应Context取消、避免同步重入,并对有序发布维持每订阅者FIFO。跨进程或跨主机请使用 adapters/redis/enginebus,它实现官方 @socket.io/cluster-engine@0.1.0 的Redis MessagePack与Channel线路。

ClusterServer 默认生成20字符base64url SID。自定义 SetGenerateId 若不满足“20字符且通过本项目SID安全字符校验”,只保证本地owner处理,不能作为跨Go实例或Node↔Go路由承诺。可用 NodeID() 识别当前节点,并通过 PendingClusterRequests()、RemoteTransportCount() 检查待响应请求和远端传输是否收敛。

官方测试证据分为三组:

  • 1–12项由 TestOfficialClusterEngine010InMemory 验证远端读写、锁、关闭、心跳、非法SID和Upgrade;
  • 13–14项由 TestOfficialClusterEngine010NodeCluster 在三个Go实例间无粘性round-robin验证心跳和二进制,属于部署行为等价,不是Node OS worker/IPC API复刻;
  • 15–18项通过Redis Go线路及真实官方Node RedisEngine 的 redis/ioredis、Node/Go双owner矩阵建立直接互操作证据,并已通过高频 -race 门禁;Cluster Engine按18/18闭合。

Go直接兼容 RedisEngine 线协议,但不提供Node专属的 setupPrimary()、NodeClusterEngine、setupPrimaryWithRedis()、primary/worker IPC、进程句柄或类继承API。官方0.1.0与Go当前实现也都没有可用的跨节点WebTransport接管入口;内部枚举包含 webtransport 不代表该路径已接通。官方快速接管固定使用EIO 4,因此普通连接的EIO 3/Socket.IO v2兼容结论不外推到跨节点快速接管。完整口径见官方测试对齐映射和集群部署。

传输方式实现

  • Polling:XHR/JSONP 传输
  • WebSocket:标准 WebSocket 传输
  • WebTransport:实验性 WebTransport 支持

事件

服务端事件
  • connection:新的客户端连接
  • connection_error:连接错误
  • initial_headers:每个连接仅在初始 Polling/直接 WebSocket 握手时触发,可修改响应头
  • headers:每次 Polling 响应和 WebSocket 握手/升级时触发,可修改响应头
  • flush:刷新缓冲区
  • drain:缓冲区已清空
Socket 事件
  • message:收到消息
  • close:连接已关闭
  • error:发生错误
  • flush:刷新写缓冲区
  • drain:写缓冲区已清空
  • packet:收到原始数据包
  • packetCreate:发送数据包前
  • heartbeat:收到 Ping/Pong

开发

前置条件
  • Go 1.26.0+
  • Make
测试
make test
调试

设置 DEBUG 环境变量:

DEBUG=engine*

参与贡献

  1. Fork 本仓库
  2. 创建功能分支(git checkout -b feature/amazing-feature)
  3. 提交改动(git commit -m 'Add some amazing feature')
  4. 推送分支(git push origin feature/amazing-feature)
  5. 创建拉取请求

许可证

采用 MIT 许可证,详情请参阅 LICENSE。

支持

Documentation

Overview

Package engine provides the core Engine.IO server implementation, including base server logic, protocol error handling, and middleware management.

Package engine provides entry points for creating and attaching Engine.IO servers, including HTTP/WebSocket/WebTransport support.

Package engine provides the Engine.IO server implementation, including HTTP/WebSocket/WebTransport handling and protocol management.

Package engine implements the Engine.IO socket, which manages client connections, transport upgrades, and protocol state.

Package engine defines core types and interfaces for Engine.IO server, including BaseServer, Server, and Socket abstractions.

Index

Constants

View Source
const (
	DefaultClusterResponseTimeout          = time.Second
	DefaultClusterNoopUpgradeInterval      = 200 * time.Millisecond
	DefaultClusterDelayedConnectionTimeout = 300 * time.Millisecond
)
View Source
const (
	// DefaultWSReadBufferSize is the default read buffer size for WebSocket connections.
	DefaultWSReadBufferSize = 1024

	// DefaultWSWriteBufferSize is the default write buffer size for WebSocket connections.
	DefaultWSWriteBufferSize = 1024
)
View Source
const (
	// DefaultUpgradeCheckInterval is the interval between upgrade readiness checks during transport upgrade.
	DefaultUpgradeCheckInterval = 100 * time.Millisecond
)
View Source
const Protocol = parser.Protocol
View Source
const VERSION = version.VERSION

Variables

View Source
var (

	// Protocol errors mappings.
	UNKNOWN_TRANSPORT            = &types.CodeMessage{Code: 0, Message: `Transport unknown`}
	UNKNOWN_SID                  = &types.CodeMessage{Code: 1, Message: `Session ID unknown`}
	BAD_HANDSHAKE_METHOD         = &types.CodeMessage{Code: 2, Message: `Bad handshake method`}
	BAD_REQUEST                  = &types.CodeMessage{Code: 3, Message: `Bad request`}
	FORBIDDEN                    = &types.CodeMessage{Code: 4, Message: `Forbidden`}
	UNSUPPORTED_PROTOCOL_VERSION = &types.CodeMessage{Code: 5, Message: `Unsupported protocol version`}
)
View Source
var ErrClusterBusClosed = errors.New("engine: cluster bus is closed")
View Source
var ErrClusterBusRequired = errors.New("engine: cluster bus is required")

Functions

This section is empty.

Types

type BaseServer

type BaseServer interface {
	types.EventEmitter

	Prototype(BaseServer)
	Proto() BaseServer

	Opts() config.ServerOptionsInterface
	// Protected
	Clients() *types.Map[string, Socket]
	ClientsCount() uint64
	// Protected
	Middlewares() []Middleware
	Transports() *types.Set[string]
	TransportsByName() map[string]transports.TransportCtor

	// Construct() should be called after calling Prototype()
	Construct(any)
	// Protected
	//
	Init()
	// Protected
	//
	// Compute the pathname of the requests that are handled by the server
	ComputePath(config.AttachOptionsInterface) string
	// Returns a list of available transports for upgrade given a certain transport.
	Upgrades(string) []string
	// Protected
	//
	// Verifies a request.
	Verify(*types.HttpContext, bool) (*types.CodeMessage, map[string]any)
	// Adds a new middleware.
	Use(Middleware)
	// Protected
	// Apply the middlewares to the request.
	ApplyMiddlewares(*types.HttpContext, func(error))
	// Closes all clients.
	Close() BaseServer
	// Protected
	Cleanup()
	// generate a socket id.
	// Overwrite this method to generate your custom socket id
	GenerateId(*types.HttpContext) string
	// Protected
	//
	// Handshakes a new client.
	Handshake(string, *types.HttpContext) (*types.CodeMessage, transports.Transport)
	// Protected
	CreateTransport(string, *types.HttpContext) (transports.Transport, error)
}

func MakeBaseServer

func MakeBaseServer() BaseServer

type ClusterBus

type ClusterBus interface {
	Subscribe(nodeID string, listener func(*ClusterMessage)) (unsubscribe func(), err error)
	Publish(context.Context, *ClusterMessage) error
}

ClusterBus transports messages between ClusterServer instances. Subscribe must deliver broadcasts and messages addressed to nodeID. The returned function removes that subscription without closing a shared bus. Publish implementations must observe ctx.Done() and return promptly. They must also enqueue delivery instead of invoking subscription listeners synchronously, while preserving FIFO order per subscription for ordered Publish calls. A listener is allowed to close any ClusterServer, including the publisher, without re-entering its in-flight publication barrier. Shutdown can cancel an in-flight publish, but Go cannot forcibly stop a bus implementation which ignores its Context.

type ClusterLockType

type ClusterLockType string

ClusterLockType identifies which half of a polling exchange is being routed.

const (
	ClusterReadLock  ClusterLockType = "read"
	ClusterWriteLock ClusterLockType = "write"
)

type ClusterMessage

type ClusterMessage struct {
	Source      string             `json:"source" msgpack:"source"`
	SenderID    string             `json:"senderId" msgpack:"senderId"`
	RecipientID string             `json:"recipientId,omitempty" msgpack:"recipientId,omitempty"`
	RequestID   uint64             `json:"requestId,omitempty" msgpack:"requestId,omitempty"`
	Type        ClusterMessageType `json:"type" msgpack:"type"`

	SID       string          `json:"sid,omitempty" msgpack:"sid,omitempty"`
	Transport string          `json:"transport,omitempty" msgpack:"transport,omitempty"`
	LockType  ClusterLockType `json:"lockType,omitempty" msgpack:"lockType,omitempty"`
	Success   bool            `json:"success,omitempty" msgpack:"success,omitempty"`
	TakeOver  bool            `json:"takeOver,omitempty" msgpack:"takeOver,omitempty"`
	Reason    string          `json:"reason,omitempty" msgpack:"reason,omitempty"`

	Packet  *ClusterPacket  `json:"packet,omitempty" msgpack:"packet,omitempty"`
	Packets []ClusterPacket `json:"packets,omitempty" msgpack:"packets,omitempty"`
}

ClusterMessage is the complete cluster-engine wire envelope. RecipientID is empty for a broadcast and set for a point-to-point response or data frame.

type ClusterMessageType

type ClusterMessageType uint8

ClusterMessageType is the wire-level operation used by ClusterServer. The values intentionally match @socket.io/cluster-engine@0.1.0.

const (
	ClusterMessageAcquireLock ClusterMessageType = iota
	ClusterMessageAcquireLockResponse
	ClusterMessageDrain
	ClusterMessagePacket
	ClusterMessageUpgrade
	ClusterMessageUpgradeResponse
	ClusterMessageClose
)

type ClusterOptions

type ClusterOptions struct {
	ResponseTimeout          time.Duration
	NoopUpgradeInterval      time.Duration
	DelayedConnectionTimeout time.Duration
}

ClusterOptions controls the distributed lock and fast-upgrade lifecycle.

type ClusterPacket

type ClusterPacket struct {
	Type    string `json:"type" msgpack:"type"`
	Data    []byte `json:"data,omitempty" msgpack:"data,omitempty"`
	HasData bool   `json:"hasData,omitempty" msgpack:"hasData,omitempty"`
	Binary  bool   `json:"binary,omitempty" msgpack:"binary,omitempty"`
	// HasCompress distinguishes an absent packet option from explicit false.
	HasCompress bool `json:"hasCompress,omitempty" msgpack:"hasCompress,omitempty"`
	Compress    bool `json:"compress,omitempty" msgpack:"compress,omitempty"`
}

ClusterPacket is the transport-independent representation of an Engine.IO packet. Data is copied before publication so buses may deliver asynchronously.

type ClusterServer

type ClusterServer interface {
	Server
	NodeID() string
	PendingClusterRequests() int
	RemoteTransportCount() int
}

ClusterServer is an Engine.IO server whose follow-up requests may arrive at any listener sharing the same ClusterBus.

func NewClusterServer

func NewClusterServer(bus ClusterBus, serverOptions any, clusterOptions *ClusterOptions) (ClusterServer, error)

NewClusterServer constructs and subscribes a cluster-aware Engine.IO server. Each server must have its own subscription, while the bus itself may be shared.

type GorillaWebSocketEngine

type GorillaWebSocketEngine struct{}

GorillaWebSocketEngine is the default WebSocket upgrader.

func (*GorillaWebSocketEngine) Upgrade

type MemoryClusterBus

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

MemoryClusterBus is a concurrency-safe, process-local implementation used for multi-listener deployments and deterministic tests. It still exercises the full cluster protocol; it does not perform sticky owner routing.

func NewMemoryClusterBus

func NewMemoryClusterBus() *MemoryClusterBus

func (*MemoryClusterBus) Close

func (b *MemoryClusterBus) Close() error

Close prevents new publications and removes every subscription.

func (*MemoryClusterBus) Publish

func (b *MemoryClusterBus) Publish(ctx context.Context, message *ClusterMessage) error

func (*MemoryClusterBus) Subscribe

func (b *MemoryClusterBus) Subscribe(nodeID string, listener func(*ClusterMessage)) (func(), error)

type Middleware

type Middleware func(*types.HttpContext, func(error))

Middleware functions are functions that have access to the *types.HttpContext and the next middleware function in the application's context cycle.

type PollingBuilder

type PollingBuilder = transports.PollingBuilder

type SendCallback

type SendCallback func(transports.Transport)

type Server

type Server interface {
	BaseServer
	// Captures upgrade requests for a http.Handler, Need to handle server shutdown disconnecting client connections.
	http.Handler

	SetHttpServer(*types.HttpServer)

	HttpServer() *types.HttpServer

	CreateTransport(string, *types.HttpContext) (transports.Transport, error)
	// Handles an Engine.IO HTTP request.
	HandleRequest(*types.HttpContext)
	// Handles an Engine.IO HTTP Upgrade.
	HandleUpgrade(*types.HttpContext)
	OnWebTransportSession(*types.HttpContext, *webtransport.Server)
	// Captures upgrade requests for a *types.HttpServer.
	Attach(*types.HttpServer, any)
}

func Attach

func Attach(server *types.HttpServer, options any) Server

Captures upgrade requests for a types.HttpServer.

func Listen

func Listen(addr string, options any, fn types.Callable) Server

Creates an http.Server exclusively used for WS upgrades.

func MakeServer

func MakeServer() Server

new server.

func New

func New(server any, args ...any) Server

func NewServer

func NewServer(opt any) Server

create server.

type Socket

type Socket interface {
	types.EventEmitter

	SetReadyState(string)

	Protocol() int
	Request() *types.HttpContext
	RemoteAddress() string
	Transport() transports.Transport
	Id() string
	ReadyState() string
	// Private
	Upgraded() bool
	// Private
	Upgrading() bool

	Construct(string, BaseServer, transports.Transport, *types.HttpContext, int)
	// Private
	//
	// Upgrades socket to the given transport
	MaybeUpgrade(transports.Transport)
	// Sends a message packet.
	Send(io.Reader, *packet.Options, SendCallback) Socket
	Write(io.Reader, *packet.Options, SendCallback) Socket
	// Closes the socket and underlying transport.
	Close(bool)
}

func MakeSocket

func MakeSocket() Socket

Client class.

func NewSocket

func NewSocket(id string, server BaseServer, transport transports.Transport, ctx *types.HttpContext, protocol int) Socket

Client class.

type TransportCtor

type TransportCtor = transports.TransportCtor
var (
	Polling      TransportCtor = &PollingBuilder{}
	WebSocket    TransportCtor = &WebSocketBuilder{}
	WebTransport TransportCtor = &WebTransportBuilder{}
)

type WebSocketBuilder

type WebSocketBuilder = transports.WebSocketBuilder

type WebTransportBuilder

type WebTransportBuilder = transports.WebTransportBuilder

Directories

Path Synopsis
Package config provides attach options for configuring how the Engine.IO server is attached to an HTTP server.
Package config provides attach options for configuring how the Engine.IO server is attached to an HTTP server.
Package errors defines error values and helpers for Engine.IO server and transport implementations.
Package errors defines error values and helpers for Engine.IO server and transport implementations.
Package transports provides builder types for Engine.IO transport registration and instantiation.
Package transports provides builder types for Engine.IO transport registration and instantiation.

Jump to

Keyboard shortcuts

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