Introduction
Zinx is a lightweight TCP server framework for Go created to simplify the development of long-lived connection servers such as game backends and IoT gateways. It provides a structured approach to handling TCP connections with message routing, connection management, and configurable worker pools.
What Zinx Does
- Manages TCP connections with automatic read/write goroutines per connection
- Routes incoming messages to handlers based on message ID
- Provides a worker pool to limit and control concurrent message processing
- Supports connection hooks (OnConnStart, OnConnStop) for lifecycle management
- Includes a TLV (Type-Length-Value) message format for structured binary protocols
Architecture Overview
Zinx uses a multi-reactor design. Each incoming TCP connection spawns dedicated reader and writer goroutines. Incoming data is parsed into messages using the TLV protocol (message ID + data length + body). Messages are dispatched to a configurable number of worker goroutines via a task queue. Routers registered by message ID handle the business logic. This design decouples I/O from processing and prevents slow handlers from blocking the connection.
Self-Hosting & Configuration
- Install with
go get github.com/aceld/zinx - Configure server via
zinx.json: host, port, max connections, worker pool size - Register routers with
server.AddRouter(msgID, handler)for each message type - Set max packet size to prevent oversized messages from consuming memory
- Use connection properties to attach session-level data to each connection
Key Features
- Message ID-based routing for clean separation of protocol handlers
- Configurable worker pool prevents goroutine explosion under high load
- Connection manager tracks all active connections with get/remove/count operations
- Hook system for executing logic on connection open and close events
- Built-in heartbeat and idle-timeout support
Comparison with Similar Tools
- gnet — lower-level event-driven framework; Zinx provides higher-level message routing and worker pools
- net/http — HTTP request-response model; Zinx is designed for persistent TCP connections
- Netty (Java) — enterprise networking framework; Zinx is simpler and Go-idiomatic
- Leaf — Go game server framework; Zinx is more general-purpose for any TCP workload
FAQ
Q: Is Zinx suitable for production use? A: Yes, it is used in game servers and IoT backends handling thousands of concurrent connections.
Q: Can Zinx handle WebSocket connections? A: Zinx focuses on raw TCP. For WebSocket, consider combining it with a WebSocket upgrade library.
Q: How does message routing work? A: Each message has a numeric ID. You register a router for each ID, and Zinx dispatches messages to the matching handler.
Q: What is the default message format? A: Zinx uses a TLV format: 4 bytes for message ID, 4 bytes for data length, followed by the data body.