Documentation
¶
Index ¶
- Constants
- Variables
- 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 ReadLengthPrefixedPacket(socket *ClientSocket, prefixSize int, maxPacketSize int) ([]byte, error)
- func ReadSeparatedPacket(socket *ClientSocket, separator []byte, maxPacketSize int) ([]byte, 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) 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 PacketHandler
- type ReadPoolEventHandler
- type Server
- type ServerMetrics
Constants ¶
const ( // PrefixInt32 32-bit prefix. PrefixInt32 = iota )
Variables ¶
var ErrPacketTooBig = errors.New("packet too big")
ErrPacketTooBig indicated that a packet has exceeded specified max size during read operation.
Functions ¶
func ReadByteArray ¶ added in v1.1.14
ReadByteArray reads byte array from given reader.
func ReadFloat32 ¶ added in v1.1.14
ReadFloat32 reads float32 from given reader.
func ReadFloat64 ¶ added in v1.1.14
ReadFloat64 reads float64 from given reader.
func ReadLengthPrefixedPacket ¶ added in v1.1.27
func ReadLengthPrefixedPacket(socket *ClientSocket, prefixSize int, maxPacketSize int) ([]byte, error)
ReadLengthPrefixedPacket tries to read packet data from socket. Packet is expected to be prefixed with little-endian encoded binary value, indicating size of the packet in bytes. Size of the prefix is given in the prefixSize argument. Packet will only be read up to maxPacketSize bytes.
func ReadSeparatedPacket ¶ added in v1.1.27
func ReadSeparatedPacket(socket *ClientSocket, separator []byte, maxPacketSize int) ([]byte, error)
ReadSeparatedPacket tries to read packet data from socket. Packet is read to the buffer until either maxPacketSize limit is exceeded or a sequence of bytes, given in the separator argument is encountered.
func ReadString ¶ added in v1.1.14
ReadString reads string from given reader.
func ReadVarInt ¶ added in v1.1.14
ReadVarInt reads var int from given reader.
func ReadVarLong ¶ added in v1.1.14
ReadVarLong reads var int64 from given reader.
func WriteByteArray ¶ added in v1.1.14
WriteByteArray writes byte array into given writer.
func WriteBytes ¶ added in v1.1.14
WriteBytes writes a byte into given writer.
func WriteFloat32 ¶ added in v1.1.14
WriteFloat32 writes float32 into given writer.
func WriteFloat64 ¶ added in v1.1.14
WriteFloat64 writes float64 into given writer.
func WriteInt16 ¶ added in v1.1.14
WriteInt16 writes int16 into given writer.
func WriteInt32 ¶ added in v1.1.14
WriteInt32 writes int32 into given writer.
func WriteInt64 ¶ added in v1.1.14
WriteInt64 writes int64 into given writer.
func WriteString ¶ added in v1.1.14
WriteString writes string into given writer.
func WriteVarInt ¶ added in v1.1.14
WriteVarInt writes var int into given writer.
Types ¶
type BulkBroadcaster ¶ added in v1.1.33
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 ¶ added in v1.1.33
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 ¶ added in v1.1.33
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 ¶ added in v1.1.33
func (b *BulkBroadcaster) Stop()
Stop stops all the workers owned by the BulkBroadcaster.
type Client ¶ added in v1.1.14
type Client struct {
// contains filtered or unexported fields
}
Client represents a TCP/TLS client.
func DialTLS ¶ added in v1.1.14
DialTLS connects to the TCP socket and performs TLS handshake, and then creates new Client. Connection is TLS secured.
func (*Client) OnClose ¶ added in v1.1.14
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 ¶ added in v1.1.14
func (cs *ClientSocket) ConnectedAt() time.Time
ConnectedAt returns an exact time the client has connected.
func (*ClientSocket) Id ¶ added in v1.1.22
func (cs *ClientSocket) Id() int64
Id returns a unique id associated with this socket.
func (*ClientSocket) IsClosed ¶ added in v1.1.27
func (cs *ClientSocket) IsClosed() bool
IsClosed check whether this connection has been closed, either by the server or the client.
func (*ClientSocket) OnClose ¶ added in v1.1.12
func (cs *ClientSocket) OnClose(handler func())
OnClose registers a handler that is called when underlying TCP connection is being closed.
func (*ClientSocket) Read ¶ added in v1.1.14
func (cs *ClientSocket) Read(b []byte) (int, error)
Read conforms to the io.Reader interface.
func (*ClientSocket) ReadsPerSecond ¶ added in v1.1.15
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) TotalRead ¶ added in v1.1.14
func (cs *ClientSocket) TotalRead() uint64
TotalRead returns a total number of bytes read through this socket.
func (*ClientSocket) TotalWritten ¶ added in v1.1.14
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 ¶ added in v1.1.27
func (cs *ClientSocket) WrapReader(wrapper func(io.Reader) io.Reader)
WrapReader allows to wrap reader object into user defined wrapper.
func (*ClientSocket) WrapWriter ¶ added in v1.1.27
func (cs *ClientSocket) WrapWriter(wrapper func(io.Writer) io.Writer)
WrapWriter allows to wrap writer object into user defined wrapper.
func (*ClientSocket) Write ¶ added in v1.1.14
func (cs *ClientSocket) Write(b []byte) (int, error)
Write conforms to the io.Writer interface.
func (*ClientSocket) WritesPerSecond ¶ added in v1.1.15
func (cs *ClientSocket) WritesPerSecond() uint64
WritesPerSecond returns a total number of bytes written through socket this second.
type ClientSocketHandler ¶ added in v1.1.18
type ClientSocketHandler func(*ClientSocket)
ClientSocketHandler represents a signature of function used by Server to handle new connections.
type ForkingStrategy ¶ added in v1.1.27
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 recvWorker pool) may be implemented on top of this interface.
func GoroutinePerConnection ¶ added in v1.1.27
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.
func WorkerPool ¶ added in v1.1.27
func WorkerPool( handler ReadPoolEventHandler, maxPoolSize int, readBufferSize int, readQuantum time.Duration, ) ForkingStrategy
WorkerPool is a forking strategy that handles new connections using a pool of worker goroutines. This strategy is expected to provide better performance than GoroutinePerConnection in scenarios in which receiving data from clients isn't critical, and can be postponed to provide lower resource overhead. New connection are added to pools that have a max size of maxPoolSize. Pools continuously read readBufferSize bytes from each of their connections for a time quantum specified by readQuantum. WorkerPool uses provided ReadPoolEventHandler as data handling implementation.
type FramingProtocol ¶ added in v1.1.37
type FramingProtocol interface { // ExtractPacket splits the buffer into packet and "the rest". // Returns ok == true if the meaningful packet has been extracted. ExtractPacket(readBuffer []byte) (packetData []byte, newReadBuffer []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 SplitBySeparator ¶ added in v1.1.37
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 PacketHandler ¶ added in v1.1.12
type PacketHandler interface { // OnAccept is called right after accepting the connection represented by the passed socket. OnAccept(socket *ClientSocket) // OnPacket is called after receiving full package by socket (according to chosen FramingProtocol). OnPacket(socket *ClientSocket, packetData []byte) }
PacketHandler is an interface over WorkerPool forking strategy. PacketHandler handles client data after packet framing performed by selected FramingProtocol.
type ReadPoolEventHandler ¶ added in v1.1.37
type ReadPoolEventHandler interface { // OnAccept is called each time new connection is accepted in the pool. OnAccept(socket *ClientSocket) // OnRead is called each time some bytes have been read from a socket. OnRead(socket *ClientSocket, data []byte) }
ReadPoolEventHandler defines interaction with socket when using WorkerPool forking strategy.
func PacketFraming ¶ added in v1.1.37
func PacketFraming(maxPacketSize int, framingProtocol FramingProtocol, handler PacketHandler) ReadPoolEventHandler
PacketFraming returns a ReadPoolEventHandler that performs packet framing, as defined by provided FramingProtocol. This allows to handle the incoming connections using PacketHandler interface. Each connection is assigned a read buffer with the maximum size equal to maxPacketSize. After reading maxPacketSize without finding a packet, all the accumulated data is discarded.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents a TCP server, and conforms to the coreutil.Service interface.
func NewServer ¶
func NewServer(config *config.Config) *Server
NewServer returns new Server instance.
func (*Server) ForkingStrategy ¶ added in v1.1.27
func (s *Server) ForkingStrategy(forkingStrategy ForkingStrategy)
ForkingStrategy sets forking strategy used by this server (see ForkingStrategy).
func (*Server) Metrics ¶ added in v1.1.22
func (s *Server) Metrics() ServerMetrics
Metrics returns aggregated server metrics.
func (*Server) OnMetricsUpdate ¶ added in v1.1.22
func (s *Server) OnMetricsUpdate(handler func())
OnMetricsUpdate sets a handler that is called everytime the server metrics are updated.
func (*Server) Sockets ¶ added in v1.1.14
func (s *Server) Sockets() []*ClientSocket
Sockets returns a list of all client sockets currently connected.
type ServerMetrics ¶ added in v1.1.22
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.