tinytcp

package
v1.0.32 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2023 License: MIT Imports: 14 Imported by: 2

Documentation

Overview

Package tinytcp provides TCP server implementation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadBool

func ReadBool(reader io.Reader) (bool, error)

ReadBool reads bool from given reader.

func ReadByte

func ReadByte(reader io.Reader) (byte, error)

ReadByte reads byte from given reader.

func ReadByteArray

func ReadByteArray(reader io.Reader) ([]byte, error)

ReadByteArray reads byte array from given reader.

func ReadBytes

func ReadBytes(reader io.Reader, n int) ([]byte, error)

ReadBytes reads bytes from given reader.

func ReadFloat32

func ReadFloat32(reader io.Reader, byteOrder ...binary.ByteOrder) (float32, error)

ReadFloat32 reads float32 from given reader.

func ReadFloat64

func ReadFloat64(reader io.Reader, byteOrder ...binary.ByteOrder) (float64, error)

ReadFloat64 reads float64 from given reader.

func ReadInt16

func ReadInt16(reader io.Reader, byteOrder ...binary.ByteOrder) (int16, error)

ReadInt16 reads int16 from given reader.

func ReadInt32

func ReadInt32(reader io.Reader, byteOrder ...binary.ByteOrder) (int32, error)

ReadInt32 reads int32 from given reader.

func ReadInt64

func ReadInt64(reader io.Reader, byteOrder ...binary.ByteOrder) (int64, error)

ReadInt64 reads int64 from given reader.

func ReadString

func ReadString(reader io.Reader) (string, error)

ReadString reads string from given reader.

func ReadVarInt

func ReadVarInt(reader io.Reader) (int, error)

ReadVarInt reads var int from given reader.

func ReadVarLong

func ReadVarLong(reader io.Reader) (int64, error)

ReadVarLong reads var int64 from given reader.

func WriteBool

func WriteBool(writer io.Writer, value bool) error

WriteBool writes a bool into given writer.

func WriteByte

func WriteByte(writer io.Writer, value byte) error

WriteByte writes a byte into given writer.

func WriteByteArray

func WriteByteArray(writer io.Writer, value []byte) error

WriteByteArray writes byte array into given writer.

func WriteBytes

func WriteBytes(writer io.Writer, value []byte) error

WriteBytes writes a byte into given writer.

func WriteFloat32

func WriteFloat32(writer io.Writer, value float32, byteOrder ...binary.ByteOrder) error

WriteFloat32 writes float32 into given writer.

func WriteFloat64

func WriteFloat64(writer io.Writer, value float64, byteOrder ...binary.ByteOrder) error

WriteFloat64 writes float64 into given writer.

func WriteInt16

func WriteInt16(writer io.Writer, value int16, byteOrder ...binary.ByteOrder) error

WriteInt16 writes int16 into given writer.

func WriteInt32

func WriteInt32(writer io.Writer, value int32, byteOrder ...binary.ByteOrder) error

WriteInt32 writes int32 into given writer.

func WriteInt64

func WriteInt64(writer io.Writer, value int64, byteOrder ...binary.ByteOrder) error

WriteInt64 writes int64 into given writer.

func WriteString

func WriteString(writer io.Writer, value string) error

WriteString writes string into given writer.

func WriteVarInt

func WriteVarInt(writer io.Writer, value int) error

WriteVarInt writes var int into given writer.

func WriteVarLong

func WriteVarLong(writer io.Writer, value int64) error

WriteVarLong writes var long 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 []*ClientSocket) 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 Dial

func Dial(address string) (*Client, error)

Dial connects to the TCP socket and creates new Client.

func DialTLS

func DialTLS(address string, tlsConfig *tls.Config) (*Client, error)

DialTLS connects to the TCP socket and performs TLS handshake, and then creates new Client. Connection is TLS secured.

func (*Client) Close

func (c *Client) Close()

Close closes the socket.

func (*Client) OnClose

func (c *Client) OnClose(handler func())

OnClose sets a handler called on closing connection (either by client or server).

func (*Client) Read

func (c *Client) Read(b []byte) (int, error)

Read conforms to the io.Reader interface.

func (*Client) Unwrap

func (c *Client) Unwrap() net.Conn

Unwrap returns underlying TCP connection.

func (*Client) UnwrapTLS

func (c *Client) UnwrapTLS() (*tls.Conn, bool)

UnwrapTLS tries to return underlying tls.Conn instance.

func (*Client) Write

func (c *Client) Write(b []byte) (int, error)

Write conforms to the io.Writer interface.

type ClientSocket

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

ClientSocket represents a dedicated socket for given TCP client.

func (*ClientSocket) Close

func (cs *ClientSocket) Close()

Close closes TCP connection.

func (*ClientSocket) ConnectedAt

func (cs *ClientSocket) ConnectedAt() time.Time

ConnectedAt returns an exact time the client has connected.

func (*ClientSocket) IsClosed

func (cs *ClientSocket) IsClosed() bool

IsClosed check whether this connection has been closed, either by the server or the client.

func (*ClientSocket) OnClose

func (cs *ClientSocket) OnClose(handler func())

OnClose registers a handler that is called when underlying TCP connection is being closed.

func (*ClientSocket) Read

func (cs *ClientSocket) Read(b []byte) (int, error)

Read conforms to the io.Reader interface.

func (*ClientSocket) ReadsPerSecond

func (cs *ClientSocket) ReadsPerSecond() uint64

ReadsPerSecond returns a total number of bytes read through socket this second.

func (*ClientSocket) RemoteAddress

func (cs *ClientSocket) RemoteAddress() string

RemoteAddress returns a remote address of the client.

func (*ClientSocket) SetReadDeadline

func (cs *ClientSocket) SetReadDeadline(deadline time.Time) error

SetReadDeadline sets read deadline for underlying socket.

func (*ClientSocket) SetWriteDeadline

func (cs *ClientSocket) SetWriteDeadline(deadline time.Time) error

SetWriteDeadline sets read deadline for underlying socket.

func (*ClientSocket) TotalRead

func (cs *ClientSocket) TotalRead() uint64

TotalRead returns a total number of bytes read through this socket.

func (*ClientSocket) TotalWritten

func (cs *ClientSocket) TotalWritten() uint64

TotalWritten returns a total number of bytes written through this socket.

func (*ClientSocket) Unwrap

func (cs *ClientSocket) Unwrap() net.Conn

Unwrap returns underlying net.Conn instance from ClientSocket.

func (*ClientSocket) UnwrapTLS

func (cs *ClientSocket) UnwrapTLS() (*tls.Conn, bool)

UnwrapTLS tries to return underlying tls.Conn instance from ClientSocket.

func (*ClientSocket) WrapReader

func (cs *ClientSocket) WrapReader(wrapper func(io.Reader) io.Reader)

WrapReader allows to wrap reader object into user defined wrapper.

func (*ClientSocket) WrapWriter

func (cs *ClientSocket) WrapWriter(wrapper func(io.Writer) io.Writer)

WrapWriter allows to wrap writer object into user defined wrapper.

func (*ClientSocket) Write

func (cs *ClientSocket) Write(b []byte) (int, error)

Write conforms to the io.Writer interface.

func (*ClientSocket) WritesPerSecond

func (cs *ClientSocket) WritesPerSecond() uint64

WritesPerSecond returns a total number of bytes written through socket this second.

type ClientSocketHandler

type ClientSocketHandler func(*ClientSocket)

ClientSocketHandler represents a signature of function used by Server to handle new connections.

func PacketFramingHandler

func PacketFramingHandler(
	framingProtocol FramingProtocol,
	handler func(ctx PacketFramingContext),
	opts ...PacketFramingOpt,
) ClientSocketHandler

PacketFramingHandler returns a ClientSocketHandler 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 *ClientSocket)

	// 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 ClientSocketHandler) 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 ok == true if the meaningful packet has been extracted.
	ExtractPacket(accumulator []byte) (packetData []byte, newAccumulator []byte, ok bool)
}

FramingProtocol defines a strategy of extracting meaningful chunks of data out of read buffer, sourced by the underlying read pool. Job of the FramingProtocol is to search for packets inside the larger byte 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 interface {
	// Socket returns underlying ClientSocket.
	Socket() *ClientSocket

	// OnPacket registers a handler that is run each time a packet is extracted from the read buffer.
	OnPacket(handler PacketHandler)
}

PacketFramingContext represents an interface that lets user subscribe on packets incoming from ClientSocket. Packet framing is specified by FramingProtocol passed to PacketFramingHandler.

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 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 NewServer

func NewServer(address string, opts ...ServerOpt) *Server

NewServer returns new Server instance.

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() []*ClientSocket

Sockets returns a list of all client sockets currently connected.

func (*Server) Start

func (s *Server) Start() error

Start implements the interface of tiny.Service.

func (*Server) Stop

func (s *Server) Stop()

Stop implements the interface of tiny.Service.

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

func MaxClients(maxClients int) ServerOpt

MaxClients denotes the maximum number of connection that can be accepted at once, -1 for no limit.

func Network added in v1.0.32

func Network(network string) ServerOpt

Network is a network parameter to pass to net.Listen.

func TLS

func TLS(cert, key string, tlsConfig ...*tls.Config) ServerOpt

TLS enables TLS mode if both cert and key point to valid TLS credentials. tlsConfig is optional.

Jump to

Keyboard shortcuts

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