Documentation
¶
Overview ¶
Package socket provides a simple TCP server framework for Go. It supports custom message encoding/decoding, asynchronous I/O operations, and connection management with heartbeat monitoring.
Index ¶
- Variables
- type Codec
- type Conn
- type ErrorAction
- type Handler
- type Logger
- type Message
- type Option
- func BufferSizeOption(size int) Option
- func CustomCodecOption(codec Codec) Option
- func HeartbeatOption(heartbeat time.Duration) Option
- func LoggerOption(logger Logger) Option
- func MessageMaxSize(size int) Option
- func OnErrorOption(cb func(error) ErrorAction) Option
- func OnMessageOption(cb func(Message) error) Option
- type Server
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidCodec is returned when no codec is provided. ErrInvalidCodec = errors.New("invalid codec callback") // ErrInvalidOnMessage is returned when no message handler is provided. ErrInvalidOnMessage = errors.New("invalid on message callback") )
Errors returned by connection operations.
var ErrBufferFull = errors.New("send buffer full")
ErrBufferFull is returned when the send buffer is full and cannot accept more messages.
Functions ¶
This section is empty.
Types ¶
type Codec ¶
type Codec interface {
// Decode reads and decodes a complete message from the reader.
// The implementation should read exactly the bytes needed for one message.
// This handles TCP packet fragmentation by allowing the codec to control
// how many bytes are read.
Decode(r io.Reader) (Message, error)
// Encode encodes a Message into raw bytes for transmission.
Encode(Message) ([]byte, error)
}
Codec is the interface for message encoding and decoding. Applications should implement this interface to define their own message serialization format (e.g., JSON, Protocol Buffers, etc.).
The Decode method reads from an io.Reader, which allows the codec to handle TCP stream reassembly by reading exactly the number of bytes needed for a complete message. This solves the TCP packet fragmentation problem.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn represents a client connection to a TCP server. It manages the underlying TCP connection, message encoding/decoding, and provides read/write loops for asynchronous communication.
func NewConn ¶
NewConn creates a new connection wrapper around the given TCP connection. It applies the provided options and validates them before returning. Returns an error if required options (codec, onMessage) are missing.
func (*Conn) Run ¶
Run starts the connection's read and write loops. It creates two goroutines for concurrent reading and writing, and blocks until an error occurs or the context is canceled. The connection is automatically closed when Run returns.
func (*Conn) Write ¶
Write sends a message through the connection without blocking. The message is encoded using the configured codec and queued for sending. Returns ErrBufferFull if the send buffer is full.
func (*Conn) WriteBlocking ¶
WriteBlocking sends a message through the connection, blocking until the message is queued or the context is canceled.
type ErrorAction ¶
type ErrorAction int
ErrorAction defines the action to take when an error occurs.
const ( // Disconnect closes the connection when an error occurs. Disconnect ErrorAction = iota // Continue suppresses the error and continues processing. Continue )
type Handler ¶
type Handler interface {
// Handle is called for each new connection.
// The implementation is responsible for managing the connection.
Handle(conn *net.TCPConn)
}
Handler is the interface for handling incoming TCP connections. Implementations should handle the connection lifecycle and message processing.
type Logger ¶
type Logger interface {
// Debug logs a debug-level message with optional key-value pairs.
Debug(msg string, args ...any)
// Info logs an info-level message with optional key-value pairs.
Info(msg string, args ...any)
// Warn logs a warning-level message with optional key-value pairs.
Warn(msg string, args ...any)
// Error logs an error-level message with optional key-value pairs.
Error(msg string, args ...any)
}
Logger is the interface for structured logging. It is designed to be compatible with *slog.Logger from the standard library. Applications can provide their own implementation or use the default slog logger.
type Message ¶
type Message interface {
// Length returns the length of the message body.
Length() int
// Body returns the raw message data.
Body() []byte
}
Message is the interface for messages transmitted over the connection. Implementations should provide the message length and body.
type Option ¶
type Option func(*options)
Option is a function that configures connection options.
func BufferSizeOption ¶
BufferSizeOption returns an Option that sets the size of the send channel buffer. A larger buffer allows more messages to be queued before blocking.
func CustomCodecOption ¶
CustomCodecOption returns an Option that sets the message codec. The codec is required and must be provided before creating a connection.
func HeartbeatOption ¶
HeartbeatOption returns an Option that sets the heartbeat interval. This determines the read/write deadline timeout (heartbeat * 2).
func LoggerOption ¶
LoggerOption returns an Option that sets the logger. If not set, the default slog logger will be used.
func MessageMaxSize ¶
MessageMaxSize returns an Option that sets the maximum message buffer size. Messages larger than this size cannot be received.
func OnErrorOption ¶
func OnErrorOption(cb func(error) ErrorAction) Option
OnErrorOption returns an Option that sets the error callback. The callback is invoked when a read/write error occurs. Return Disconnect to close the connection, or Continue to suppress the error.
func OnMessageOption ¶
OnMessageOption returns an Option that sets the message handler callback. This callback is required and is invoked for each received message.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents a TCP server that listens for incoming connections.
func New ¶
New creates a new TCP server bound to the specified address. Returns an error if the address cannot be bound.
func (*Server) Close ¶
Close stops the server by closing the underlying listener. Any blocked Accept calls will return with an error.