Documentation ¶
Overview ¶
Package tinytcp provides TCP server implementation.
Index ¶
- func ReadBool(reader io.Reader) (bool, error)
- func ReadByte(reader io.Reader) (byte, error)
- func ReadByteArray(reader io.Reader) ([]byte, error)
- func ReadBytes(reader io.Reader, n int) ([]byte, error)
- func ReadFloat32(reader io.Reader, byteOrder ...binary.ByteOrder) (float32, error)
- func ReadFloat64(reader io.Reader, byteOrder ...binary.ByteOrder) (float64, error)
- func ReadInt16(reader io.Reader, byteOrder ...binary.ByteOrder) (int16, error)
- func ReadInt32(reader io.Reader, byteOrder ...binary.ByteOrder) (int32, error)
- func ReadInt64(reader io.Reader, byteOrder ...binary.ByteOrder) (int64, error)
- func ReadString(reader io.Reader) (string, error)
- func ReadVarInt(reader io.Reader) (int, error)
- func ReadVarLong(reader io.Reader) (int64, error)
- func WriteBool(writer io.Writer, value bool) error
- func WriteByte(writer io.Writer, value byte) error
- func WriteByteArray(writer io.Writer, value []byte) error
- func WriteBytes(writer io.Writer, value []byte) error
- func WriteFloat32(writer io.Writer, value float32, byteOrder ...binary.ByteOrder) error
- func WriteFloat64(writer io.Writer, value float64, byteOrder ...binary.ByteOrder) error
- func WriteInt16(writer io.Writer, value int16, byteOrder ...binary.ByteOrder) error
- func WriteInt32(writer io.Writer, value int32, byteOrder ...binary.ByteOrder) error
- func WriteInt64(writer io.Writer, value int64, byteOrder ...binary.ByteOrder) error
- func WriteString(writer io.Writer, value string) error
- func WriteVarInt(writer io.Writer, value int) error
- func WriteVarLong(writer io.Writer, value int64) error
- type BulkBroadcaster
- type Client
- type ConnectedSocket
- func (cs *ConnectedSocket) Close() error
- func (cs *ConnectedSocket) ConnectedAt() time.Time
- func (cs *ConnectedSocket) IsClosed() bool
- func (cs *ConnectedSocket) OnClose(handler func())
- func (cs *ConnectedSocket) Read(b []byte) (int, error)
- func (cs *ConnectedSocket) ReadsPerSecond() uint64
- func (cs *ConnectedSocket) RemoteAddress() string
- func (cs *ConnectedSocket) SetReadDeadline(deadline time.Time) error
- func (cs *ConnectedSocket) SetWriteDeadline(deadline time.Time) error
- func (cs *ConnectedSocket) TotalRead() uint64
- func (cs *ConnectedSocket) TotalWritten() uint64
- func (cs *ConnectedSocket) Unwrap() net.Conn
- func (cs *ConnectedSocket) UnwrapTLS() (*tls.Conn, bool)
- func (cs *ConnectedSocket) WrapReader(wrapper func(io.Reader) io.Reader)
- func (cs *ConnectedSocket) WrapWriter(wrapper func(io.Writer) io.Writer)
- func (cs *ConnectedSocket) Write(b []byte) (int, error)
- func (cs *ConnectedSocket) WritesPerSecond() uint64
- type ConnectedSocketHandler
- type ForkingStrategy
- type FramingProtocol
- type PacketFramingConfig
- type PacketFramingContext
- type PacketFramingOpt
- type PacketHandler
- type PrefixLength
- type Server
- type ServerConfig
- type ServerMetrics
- type ServerOpt
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReadByteArray ¶
ReadByteArray reads byte array from given reader.
func ReadFloat32 ¶
ReadFloat32 reads float32 from given reader.
func ReadFloat64 ¶
ReadFloat64 reads float64 from given reader.
func ReadString ¶
ReadString reads string from given reader.
func ReadVarInt ¶
ReadVarInt reads var int from given reader.
func ReadVarLong ¶
ReadVarLong reads var int64 from given reader.
func WriteByteArray ¶
WriteByteArray writes byte array into given writer.
func WriteBytes ¶
WriteBytes writes a byte into given writer.
func WriteFloat32 ¶
WriteFloat32 writes float32 into given writer.
func WriteFloat64 ¶
WriteFloat64 writes float64 into given writer.
func WriteInt16 ¶
WriteInt16 writes int16 into given writer.
func WriteInt32 ¶
WriteInt32 writes int32 into given writer.
func WriteInt64 ¶
WriteInt64 writes int64 into given writer.
func WriteString ¶
WriteString writes string into given writer.
func WriteVarInt ¶
WriteVarInt writes var int into given writer.
Types ¶
type BulkBroadcaster ¶
type BulkBroadcaster struct {
// contains filtered or unexported fields
}
BulkBroadcaster is a high-performance data pump for broadcasting server packets to multiple clients. BulkBroadcaster uses an underlying workers pool. Workers are goroutines that constantly fetch data to broadcast and are responsible for sending fetched data to their subset of clients, specified as recipients. This approach is inefficient for small numbers of recipients but may be useful for some less-common scenarios, that involve interacting with huge number of clients.
func StartBulkBroadcaster ¶
func StartBulkBroadcaster(workersCount, poolSize int, writeQuantum time.Duration) *BulkBroadcaster
StartBulkBroadcaster creates and starts BulkBroadcaster. workersCount is a number of workers to start. poolSize is a number of messages to schedule for a single worker in one iteration. writeQuantum is the maximum amount of time that should be allocated to Write() operation on a single socket.
func (*BulkBroadcaster) Broadcast ¶
func (b *BulkBroadcaster) Broadcast(data []byte, targets []*ConnectedSocket) error
Broadcast schedules data to be written to all the sockets specified by targets array. The work will be split between workers for efficient processing.
func (*BulkBroadcaster) Stop ¶
func (b *BulkBroadcaster) Stop()
Stop stops all the workers owned by the BulkBroadcaster.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a TCP/TLS client.
func DialTLS ¶
DialTLS connects to the TCP socket and performs TLS handshake, and then creates new Client. Connection is TLS secured.
func (*Client) OnClose ¶
func (c *Client) OnClose(handler func())
OnClose sets a handler called on closing connection (either by client or server).
type ConnectedSocket ¶ added in v1.0.33
type ConnectedSocket struct {
// contains filtered or unexported fields
}
ConnectedSocket represents a dedicated socket for given TCP client.
func (*ConnectedSocket) Close ¶ added in v1.0.33
func (cs *ConnectedSocket) Close() error
Close closes underlying TCP connection and executes all the registered close handlers. This method always returns nil, but its signature is meant to stick to the io.Closer interface.
func (*ConnectedSocket) ConnectedAt ¶ added in v1.0.33
func (cs *ConnectedSocket) ConnectedAt() time.Time
ConnectedAt returns an exact time the socket has connected.
func (*ConnectedSocket) IsClosed ¶ added in v1.0.33
func (cs *ConnectedSocket) IsClosed() bool
IsClosed check whether this connection has been closed, either by the server or the client.
func (*ConnectedSocket) OnClose ¶ added in v1.0.33
func (cs *ConnectedSocket) OnClose(handler func())
OnClose registers a handler that is called when underlying TCP connection is being closed.
func (*ConnectedSocket) Read ¶ added in v1.0.33
func (cs *ConnectedSocket) Read(b []byte) (int, error)
Read conforms to the io.Reader interface.
func (*ConnectedSocket) ReadsPerSecond ¶ added in v1.0.33
func (cs *ConnectedSocket) ReadsPerSecond() uint64
ReadsPerSecond returns a total number of bytes read through socket this second.
func (*ConnectedSocket) RemoteAddress ¶ added in v1.0.33
func (cs *ConnectedSocket) RemoteAddress() string
RemoteAddress returns a remote address of the socket.
func (*ConnectedSocket) SetReadDeadline ¶ added in v1.0.33
func (cs *ConnectedSocket) SetReadDeadline(deadline time.Time) error
SetReadDeadline sets read deadline for underlying socket.
func (*ConnectedSocket) SetWriteDeadline ¶ added in v1.0.33
func (cs *ConnectedSocket) SetWriteDeadline(deadline time.Time) error
SetWriteDeadline sets read deadline for underlying socket.
func (*ConnectedSocket) TotalRead ¶ added in v1.0.33
func (cs *ConnectedSocket) TotalRead() uint64
TotalRead returns a total number of bytes read through this socket.
func (*ConnectedSocket) TotalWritten ¶ added in v1.0.33
func (cs *ConnectedSocket) TotalWritten() uint64
TotalWritten returns a total number of bytes written through this socket.
func (*ConnectedSocket) Unwrap ¶ added in v1.0.33
func (cs *ConnectedSocket) Unwrap() net.Conn
Unwrap returns underlying net.Conn instance from ConnectedSocket.
func (*ConnectedSocket) UnwrapTLS ¶ added in v1.0.33
func (cs *ConnectedSocket) UnwrapTLS() (*tls.Conn, bool)
UnwrapTLS tries to return underlying tls.Conn instance from ConnectedSocket.
func (*ConnectedSocket) WrapReader ¶ added in v1.0.33
func (cs *ConnectedSocket) WrapReader(wrapper func(io.Reader) io.Reader)
WrapReader allows to wrap reader object into user defined wrapper.
func (*ConnectedSocket) WrapWriter ¶ added in v1.0.33
func (cs *ConnectedSocket) WrapWriter(wrapper func(io.Writer) io.Writer)
WrapWriter allows to wrap writer object into user defined wrapper.
func (*ConnectedSocket) Write ¶ added in v1.0.33
func (cs *ConnectedSocket) Write(b []byte) (int, error)
Write conforms to the io.Writer interface.
func (*ConnectedSocket) WritesPerSecond ¶ added in v1.0.33
func (cs *ConnectedSocket) WritesPerSecond() uint64
WritesPerSecond returns a total number of bytes written through socket this second.
type ConnectedSocketHandler ¶ added in v1.0.33
type ConnectedSocketHandler func(*ConnectedSocket)
ConnectedSocketHandler represents a signature of function used by Server to handle new connections.
func PacketFramingHandler ¶
func PacketFramingHandler( framingProtocol FramingProtocol, handler func(ctx *PacketFramingContext), opts ...PacketFramingOpt, ) ConnectedSocketHandler
PacketFramingHandler returns a ConnectedSocketHandler that handles packet framing according to given FramingProtocol.
type ForkingStrategy ¶
type ForkingStrategy interface { // OnStart is called once, after server start. OnStart() // OnAccept is called for every connection accepted by the server. // The implementation should handle all the interactions with the socket, // closing it after use and recovering from any potential panic. OnAccept(socket *ConnectedSocket) // OnMetricsUpdate is called every time the server updates its metrics. OnMetricsUpdate(metrics *ServerMetrics) // OnStop is called once, after server stops. OnStop() }
ForkingStrategy defines the way new connections are handled by the associated TCP server. Most naive implementation is to start a new goroutine for each new connection, and make this goroutine responsible for the whole lifecycle of the connection. This implementation might not fit the needs of some highly-concurrent servers, so other implementations (like worker pool) may be implemented on top of this interface.
func GoroutinePerConnection ¶
func GoroutinePerConnection(handler ConnectedSocketHandler) ForkingStrategy
GoroutinePerConnection is the most naive implementation of the ForkingStrategy. This is the recommended implementation for most of the general-purpose TCP servers. It starts a new goroutine for every new connection. The handler associated with the connection will be responsible for handling blocking operations on this connection. Connections are automatically closed after their handler finishes.
type FramingProtocol ¶
type FramingProtocol interface { // ExtractPacket splits the buffer into packet and "the rest". // Returns extracted == true if the meaningful packet has been extracted. ExtractPacket(accumulator []byte) (packet []byte, rest []byte, extracted bool) }
FramingProtocol defines a strategy of extracting meaningful chunks of data out of read buffer.
func LengthPrefixedFraming ¶
func LengthPrefixedFraming(prefixLength PrefixLength) FramingProtocol
LengthPrefixedFraming is a FramingProtocol that expects each packet to be prefixed with its length in bytes. Length is expected to be provided as binary encoded number with size and endianness specified by value provided as prefixLength argument.
func SplitBySeparator ¶
func SplitBySeparator(separator []byte) FramingProtocol
SplitBySeparator is a FramingProtocol strategy that expects each packet to end with a sequence of bytes given as separator. It is a good strategy for tasks like handling Telnet sessions (packets are separated by a newline).
type PacketFramingConfig ¶ added in v1.0.31
type PacketFramingConfig struct {
// contains filtered or unexported fields
}
PacketFramingConfig hold configuration for PacketFramingHandler.
type PacketFramingContext ¶
type PacketFramingContext struct {
// contains filtered or unexported fields
}
PacketFramingContext represents an interface that lets user subscribe on packets incoming from ConnectedSocket. Packet framing is specified by FramingProtocol passed to PacketFramingHandler.
func (*PacketFramingContext) OnPacket ¶
func (p *PacketFramingContext) OnPacket(handler PacketHandler)
OnPacket registers a handler that is run each time a packet is extracted from the read buffer.
func (*PacketFramingContext) Socket ¶
func (p *PacketFramingContext) Socket() *ConnectedSocket
Socket returns underlying ConnectedSocket.
type PacketFramingOpt ¶ added in v1.0.31
type PacketFramingOpt = func(*PacketFramingConfig)
PacketFramingOpt represents an option to be specified to PacketFramingHandler.
func MaxPacketSize ¶ added in v1.0.31
func MaxPacketSize(size int) PacketFramingOpt
MaxPacketSize sets a maximal size of a packet (default: 16KiB).
func MinReadSpace ¶ added in v1.0.43
func MinReadSpace(space int) PacketFramingOpt
MinReadSpace sets a minimal space in read buffer that's needed to fit another Read() into it, without allocating auxiliary buffer (default: 1KiB or 1/4 of ReadBufferSize).
func ReadBufferSize ¶ added in v1.0.31
func ReadBufferSize(size int) PacketFramingOpt
ReadBufferSize sets a size of read buffer (default: 4KiB).
type PacketHandler ¶
type PacketHandler func(packet []byte)
PacketHandler is a function to be called after receiving packet data.
type PrefixLength ¶
type PrefixLength int
PrefixLength denotes the length of the prefix used to specify packet length.
const ( // PrefixVarInt represents a VarInt prefix. PrefixVarInt PrefixLength = iota // PrefixVarLong represents a VarLong prefix. PrefixVarLong // PrefixInt16_BE 16-bit prefix (Big Endian). PrefixInt16_BE // PrefixInt16_LE 16-bit prefix (Little Endian). PrefixInt16_LE // PrefixInt32_BE 32-bit prefix (Big Endian). PrefixInt32_BE // PrefixInt32_LE 32-bit prefix (Little Endian). PrefixInt32_LE // PrefixInt64_BE 64-bit prefix (Big Endian). PrefixInt64_BE // PrefixInt64_LE 64-bit prefix (Little Endian). PrefixInt64_LE )
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents a TCP server, and conforms to the tiny.Service interface.
func (*Server) ForkingStrategy ¶
func (s *Server) ForkingStrategy(forkingStrategy ForkingStrategy)
ForkingStrategy sets forking strategy used by this server (see ForkingStrategy).
func (*Server) Metrics ¶
func (s *Server) Metrics() ServerMetrics
Metrics returns aggregated server metrics.
func (*Server) OnMetricsUpdate ¶
func (s *Server) OnMetricsUpdate(handler func())
OnMetricsUpdate sets a handler that is called everytime the server metrics are updated.
func (*Server) Sockets ¶
func (s *Server) Sockets() []*ConnectedSocket
Sockets returns a list of all client sockets currently connected.
type ServerConfig ¶
type ServerConfig struct { // Network is a network parameter to pass to net.Listen (default: "tcp"). Network string // Max clients denotes the maximum number of connection that can be accepted at once, -1 for no limit (default: -1). MaxClients int // TLSCert is a path to TLS certificate to use. When specified with TLSKey - enables TLS mode. TLSCert string // TLSKey is a path to TLS key to use. When specified with TLSCert - enables TLS mode. TLSKey string // TLSConfig is an optional TLS configuration to pass when using TLS mode. TLSConfig *tls.Config // contains filtered or unexported fields }
ServerConfig holds a configuration for NewServer.
type ServerMetrics ¶
type ServerMetrics struct { // TotalRead is total number of bytes read by server since start. TotalRead uint64 // TotalRead is total number of bytes written by server since start. TotalWritten uint64 // ReadsPerSecond is total number of bytes read by server last second. ReadsPerSecond uint64 // ReadsPerSecond is total number of bytes written by server last second. WritesPerSecond uint64 // Connections is total number of clients connected during last second. Connections int // MaxConnections is maximum number of clients connected at a single time. MaxConnections int // Goroutines is total number of goroutines active during last second. Goroutines int // MaxGoroutines is maximum number of goroutines active at a single time. MaxGoroutines int }
ServerMetrics contains basic metrics gathered from TCP server.
type ServerOpt ¶
type ServerOpt func(*ServerConfig)
ServerOpt is an option to be specified to NewServer.
func MaxClients ¶
MaxClients denotes the maximum number of connection that can be accepted at once, -1 for no limit.