engine

package module
v3.0.0-rc.11 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 21 Imported by: 1

README

Engine.IO: The Realtime Engine for Golang

Go Reference Go Report Card

Overview

Engine.IO is a transport-based cross-browser/cross-device bi-directional communication layer implementation for Socket.IO in Go. It abstracts away the differences between various transports (WebSocket, Polling, WebTransport) and provides a unified API.

Features

  • Multiple transport support (WebSocket, Polling, WebTransport)
  • Automatic transport upgrade
  • Stateful connections with heartbeat mechanism
  • Binary data support
  • Multiplexing support
  • Auto-reconnection support
  • Cross-browser compatibility
  • Engine.IO protocol v3 and v4 support

Installation

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

Quick Start

package main

import (
    "github.com/zishang520/socket.io/servers/engine/v3"
    "github.com/zishang520/socket.io/servers/engine/v3/config"
    "github.com/zishang520/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 {}
}

Usage

Server Initialization Methods
  1. Direct Listening
  2. HTTP Server Integration
  3. Custom Request Handling
  4. WebSocket Integration
  5. WebTransport Support

Configuration

Server Options
opts := &config.ServerOptions{}
opts.SetPingTimeout(20_000 * time.Millisecond)
opts.SetPingInterval(25_000 * time.Millisecond)
opts.SetUpgradeTimeout(10_000 * time.Millisecond)
opts.SetMaxHttpBufferSize(1e6)
// ...

Transport Implementations

  • Polling: XHR/JSONP transport
  • WebSocket: Standard WebSocket transport
  • WebTransport: Experimental WebTransport support

Events

Server Events
  • connection: New client connection
  • connection_error: Connection error
  • flush: Buffer flush
  • drain: Buffer drain
Socket Events
  • message: Incoming message
  • close: Connection closed
  • error: Error occurred
  • flush: Write buffer flush
  • drain: Write buffer drained
  • packet: Raw packet received
  • packetCreate: Before packet send
  • heartbeat: Ping/Pong received

Development

Prerequisites
  • Go 1.24.1+
  • Make
Testing
make test
Debugging

Set the DEBUG environment variable:

DEBUG=engine*

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see LICENSE for details.

Support

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 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: 4, Message: `Unsupported protocol version`}
)

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, error)
	// 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 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