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) (float32, error)
- func ReadFloat64(reader io.Reader) (float64, error)
- func ReadInt16(reader io.Reader) (int16, error)
- func ReadInt32(reader io.Reader) (int32, error)
- func ReadInt64(reader io.Reader) (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) error
- func WriteFloat64(writer io.Writer, value float64) error
- func WriteInt16(writer io.Writer, value int16) error
- func WriteInt32(writer io.Writer, value int32) error
- func WriteInt64(writer io.Writer, value int64) 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 ClientSocket
- func (cs *ClientSocket) Close()
- func (cs *ClientSocket) ConnectedAt() time.Time
- func (cs *ClientSocket) Id() int64
- func (cs *ClientSocket) IsClosed() bool
- func (cs *ClientSocket) OnClose(handler func())
- func (cs *ClientSocket) Read(b []byte) (int, error)
- func (cs *ClientSocket) ReadsPerSecond() uint64
- func (cs *ClientSocket) RemoteAddress() string
- func (cs *ClientSocket) SetReadDeadline(deadline time.Time) error
- func (cs *ClientSocket) SetWriteDeadline(deadline time.Time) error
- func (cs *ClientSocket) TotalRead() uint64
- func (cs *ClientSocket) TotalWritten() uint64
- func (cs *ClientSocket) Unwrap() net.Conn
- func (cs *ClientSocket) UnwrapTLS() (*tls.Conn, bool)
- func (cs *ClientSocket) WrapReader(wrapper func(io.Reader) io.Reader)
- func (cs *ClientSocket) WrapWriter(wrapper func(io.Writer) io.Writer)
- func (cs *ClientSocket) Write(b []byte) (int, error)
- func (cs *ClientSocket) WritesPerSecond() uint64
- type ClientSocketHandler
- type ForkingStrategy
- type FramingProtocol
- type ListenMode
- type PacketFramingContext
- 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 []*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 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 ClientSocket ¶
type ClientSocket struct {
// contains filtered or unexported fields
}
ClientSocket represents a dedicated socket for given TCP client.
func (*ClientSocket) ConnectedAt ¶
func (cs *ClientSocket) ConnectedAt() time.Time
ConnectedAt returns an exact time the client has connected.
func (*ClientSocket) Id ¶
func (cs *ClientSocket) Id() int64
Id returns a unique id associated with this socket.
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, readBufferSize int, maxPacketSize int, handler func(ctx PacketFramingContext), ) 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 ListenMode ¶
type ListenMode = int
ListenMode is a mode in which the server starts listening.
const ( // Both means listen in both IPv4, IPv6 modes. Both ListenMode = iota // IPv4_Only means listen in IPv4 mode only. IPv4_Only // IPv6_Only means listen in IPv6 mode only. IPv6_Only )
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 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 ( // PrefixInt32_BE 32-bit prefix (Big Endian). PrefixInt32_BE PrefixLength = iota // PrefixInt32_LE 32-bit prefix (Little Endian). PrefixInt32_LE )
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents a TCP server, and conforms to the coreutil.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() []*ClientSocket
Sockets returns a list of all client sockets currently connected.
type ServerConfig ¶
type ServerConfig struct { // Address is an address to bind server socket to (default: "0.0.0.0:7000"). Address string // Mode is a mode in which the server starts listening - IPv4_Only, IPv6_Only or Both (default: Both). Mode ListenMode // 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 }
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.
func Mode ¶
func Mode(mode ListenMode) ServerOpt
Mode is a mode in which the server starts listening - IPv4_Only, IPv6_Only or Both.