Documentation ¶
Overview ¶
Teleport is a versatile, high-performance and flexible TCP socket framework. It can be used for peer-peer, rpc, gateway, micro services, push services, game services and so on.
Copyright 2015-2017 HenryLee. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Index ¶
- Constants
- Variables
- func Criticalf(format string, args ...interface{})
- func Debugf(format string, args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatalf(format string, args ...interface{})
- func Go(fn func()) bool
- func GraceSignal()
- func Infof(format string, args ...interface{})
- func Noticef(format string, args ...interface{})
- func Panicf(format string, args ...interface{})
- func Printf(format string, args ...interface{})
- func Reboot(timeout ...time.Duration)
- func SetGlobalBodyCodec(codecId byte)
- func SetGopool(maxGoroutinesAmount int, maxGoroutineIdleDuration time.Duration)
- func SetLogger(logger Logger)
- func SetRawlogLevel(level string)
- func SetShutdown(timeout time.Duration, firstSweep, beforeExiting func() error)
- func Shutdown(timeout ...time.Duration)
- func Tracef(format string, args ...interface{})
- func TypeText(typ byte) string
- func Warnf(format string, args ...interface{})
- type Handler
- type HandlersMaker
- type Logger
- type Peer
- func (p *Peer) Close() (err error)
- func (p *Peer) CountSession() int
- func (p *Peer) Dial(addr string, protoFunc ...socket.ProtoFunc) (Session, *Rerror)
- func (p *Peer) DialContext(ctx context.Context, addr string, protoFunc ...socket.ProtoFunc) (Session, *Rerror)
- func (p *Peer) GetSession(sessionId string) (Session, bool)
- func (p *Peer) Listen(protoFunc ...socket.ProtoFunc) error
- func (p *Peer) RangeSession(fn func(sess Session) bool)
- func (p *Peer) ServeConn(conn net.Conn, protoFunc ...socket.ProtoFunc) Session
- type PeerConfig
- type Plugin
- type PluginContainer
- type PostAcceptPlugin
- type PostDialPlugin
- type PostDisconnectPlugin
- type PostReadPullBodyPlugin
- type PostReadPullHeaderPlugin
- type PostReadPushBodyPlugin
- type PostReadPushHeaderPlugin
- type PostReadReplyBodyPlugin
- type PostReadReplyHeaderPlugin
- type PostRegPlugin
- type PostSession
- type PostWritePullPlugin
- type PostWritePushPlugin
- type PostWriteReplyPlugin
- type PreReadHeaderPlugin
- type PreReadPullBodyPlugin
- type PreReadPushBodyPlugin
- type PreReadReplyBodyPlugin
- type PreSession
- type PreWritePullPlugin
- type PreWritePushPlugin
- type PreWriteReplyPlugin
- type PullCmd
- func (c *PullCmd) CostTime() time.Duration
- func (c *PullCmd) Ip() string
- func (c *PullCmd) Output() *socket.Packet
- func (c *PullCmd) Peer() *Peer
- func (c *PullCmd) Public() goutil.Map
- func (c *PullCmd) PublicLen() int
- func (c *PullCmd) Rerror() *Rerror
- func (c *PullCmd) Result() (interface{}, *Rerror)
- func (c *PullCmd) Session() Session
- type PullCtx
- type PushCtx
- type ReadCtx
- type Rerror
- type Router
- type Session
- type SessionHub
- type UnknownPullCtx
- type UnknownPushCtx
- type WriteCtx
Constants ¶
const ( TypeUndefined byte = 0 TypePull byte = 1 TypeReply byte = 2 // reply to pull TypePush byte = 3 )
Packet types
const ( CodeDialFailed = 105 CodeConnClosed = 102 CodeWriteFailed = 104 CodeBadPacket = 400 CodeNotFound = 404 CodeNotImplemented = 501 )
Internal Framework Rerror code. Note: Recommended custom code is greater than 1000.
const MetaRerrorKey = "X-Reply-Error"
Variables ¶
var DefaultProtoFunc = socket.DefaultProtoFunc
DefaultProtoFunc gets the default builder of socket communication protocol
func DefaultProtoFunc() socket.ProtoFunc
var ErrConnClosed = errors.New("connection is closed")
ErrConnClosed connection is closed error.
var ErrListenClosed = errors.New("listener is closed")
ErrListenClosed listener is closed error.
var FirstSweep, BeforeExiting func() error
FirstSweep is first executed. BeforeExiting is executed before process exiting. Usage: share github.com/henrylee2cn/goutil/graceful with other project.
var GetPacket = socket.GetPacket
GetPacket gets a *Packet form packet stack. Note:
newBodyFunc is only for reading form connection; settings are only for writing to connection. func GetPacket(settings ...socket.PacketSetting) *socket.Packet
var GetReadLimit = socket.PacketSizeLimit
GetReadLimit gets the packet size upper limit of reading.
PacketSizeLimit() uint32
var PutPacket = socket.PutPacket
PutPacket puts a *socket.Packet to packet stack.
func PutPacket(p *socket.Packet)
var SetDefaultProtoFunc = socket.SetDefaultProtoFunc
SetDefaultProtoFunc sets the default builder of socket communication protocol
func SetDefaultProtoFunc(protoFunc socket.ProtoFunc)
var SetReadLimit = socket.SetPacketSizeLimit
SetPacketSizeLimit sets max packet size. If maxSize<=0, set it to max uint32.
func SetPacketSizeLimit(maxPacketSize uint32)
var SetTCPReadBuffer = socket.SetTCPReadBuffer
SetReadBuffer sets the size of the operating system's receive buffer associated with the *net.TCP connection. Note: Uses the default value, if bytes=1.
func SetTCPReadBuffer(bytes int)
var SetTCPWriteBuffer = socket.SetTCPWriteBuffer
SetWriteBuffer sets the size of the operating system's transmit buffer associated with the *net.TCP connection. Note: Uses the default value, if bytes=1.
func SetTCPWriteBuffer(bytes int)
Functions ¶
func Criticalf ¶
func Criticalf(format string, args ...interface{})
Criticalf logs a message using CRITICAL as log level.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs a message using DEBUG as log level.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs a message using ERROR as log level.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf is equivalent to l.Criticalf followed by a call to os.Exit(1).
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs a message using INFO as log level.
func Noticef ¶
func Noticef(format string, args ...interface{})
Noticef logs a message using NOTICE as log level.
func Panicf ¶
func Panicf(format string, args ...interface{})
Panicf is equivalent to l.Criticalf followed by a call to panic().
func Printf ¶
func Printf(format string, args ...interface{})
Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.
func SetGlobalBodyCodec ¶
func SetGlobalBodyCodec(codecId byte)
SetDefaultBodyCodec set the default header codec. Note:
If the codec.Codec named 'codecId' is not registered, it will panic; It is not safe to call it concurrently.
func SetGopool ¶
SetGopool set or reset go pool config. Note: Make sure to call it before calling NewPeer() and Go()
func SetLogger ¶
func SetLogger(logger Logger)
SetLogger sets global logger. Note: Concurrent is not safe!
func SetRawlogLevel ¶
func SetRawlogLevel(level string)
SetRawlogLevel sets the default logger's level. Note: Concurrent is not safe!
func SetShutdown ¶
SetShutdown sets the function which is called after the process shutdown, and the time-out period for the process shutdown. If 0<=timeout<5s, automatically use 'MinShutdownTimeout'(5s). If timeout<0, indefinite period. 'firstSweep' is first executed. 'beforeExiting' is executed before process exiting.
func Shutdown ¶
Shutdown closes all the frame process gracefully. Parameter timeout is used to reset time-out period for the process shutdown.
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef logs a message using TRACE as log level.
Types ¶
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler pull or push handler type info
func (*Handler) ArgElemType ¶
ArgElemType returns the handler arg elem type.
type HandlersMaker ¶
type HandlersMaker func(string, interface{}, PluginContainer) ([]*Handler, error)
HandlersMaker makes []*Handler
type Logger ¶
type Logger interface { // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. Printf(format string, args ...interface{}) // Fatalf is equivalent to Criticalf followed by a call to os.Exit(1). Fatalf(format string, args ...interface{}) // Panicf is equivalent to Criticalf followed by a call to panic(). Panicf(format string, args ...interface{}) // Criticalf logs a message using CRITICAL as log level. Criticalf(format string, args ...interface{}) // Errorf logs a message using ERROR as log level. Errorf(format string, args ...interface{}) // Warnf logs a message using WARNING as log level. Warnf(format string, args ...interface{}) // Noticef logs a message using NOTICE as log level. Noticef(format string, args ...interface{}) // Infof logs a message using INFO as log level. Infof(format string, args ...interface{}) // Debugf logs a message using DEBUG as log level. Debugf(format string, args ...interface{}) // Tracef logs a message using TRACE as log level. Tracef(format string, args ...interface{}) }
Logger interface
type Peer ¶
type Peer struct { PullRouter *Router PushRouter *Router // contains filtered or unexported fields }
Peer peer which is server or client.
func (*Peer) CountSession ¶
CountSession returns the number of sessions.
func (*Peer) DialContext ¶
func (p *Peer) DialContext(ctx context.Context, addr string, protoFunc ...socket.ProtoFunc) (Session, *Rerror)
DialContext connects with the peer of the destination address, using the provided context.
func (*Peer) GetSession ¶
GetSession gets the session by id.
func (*Peer) RangeSession ¶
RangeSession ranges all sessions. If fn returns false, stop traversing.
type PeerConfig ¶
type PeerConfig struct { TlsCertFile string `yaml:"tls_cert_file" ini:"tls_cert_file" comment:"TLS certificate file path"` TlsKeyFile string `yaml:"tls_key_file" ini:"tls_key_file" comment:"TLS key file path"` DefaultReadTimeout time.Duration `yaml:"default_read_timeout" ini:"default_read_timeout" comment:"Default maximum duration for reading; ns,µs,ms,s,m,h"` DefaultWriteTimeout time.Duration `yaml:"default_write_timeout" ini:"default_write_timeout" comment:"Default maximum duration for writing; ns,µs,ms,s,m,h"` SlowCometDuration time.Duration `yaml:"slow_comet_duration" ini:"slow_comet_duration" comment:"Slow operation alarm threshold; ns,µs,ms,s ..."` DefaultBodyCodec string `yaml:"default_body_codec" ini:"default_body_codec" comment:"Default body codec type id"` PrintBody bool `yaml:"print_body" ini:"print_body" comment:"Is print body or not"` CountTime bool `yaml:"count_time" ini:"count_time" comment:"Is count cost time or not"` DefaultDialTimeout time.Duration `` /* 141-byte string literal not displayed */ ListenAddrs []string `yaml:"listen_addrs" ini:"listen_addrs" comment:"Listen addresses; for server role"` }
PeerConfig peer config Note:
yaml tag is used for github.com/henrylee2cn/cfgo ini tag is used for github.com/henrylee2cn/ini
type PluginContainer ¶
type PluginContainer interface { Add(plugins ...Plugin) error Remove(pluginName string) error GetByName(pluginName string) Plugin GetAll() []Plugin PostReg(*Handler) *Rerror PostDial(PreSession) *Rerror PostAccept(PreSession) *Rerror PreWritePull(WriteCtx) *Rerror PostWritePull(WriteCtx) *Rerror PreWriteReply(WriteCtx) *Rerror PostWriteReply(WriteCtx) *Rerror PreWritePush(WriteCtx) *Rerror PostWritePush(WriteCtx) *Rerror PreReadHeader(ReadCtx) *Rerror PostReadPullHeader(ReadCtx) *Rerror PreReadPullBody(ReadCtx) *Rerror PostReadPullBody(ReadCtx) *Rerror PostReadPushHeader(ReadCtx) *Rerror PreReadPushBody(ReadCtx) *Rerror PostReadPushBody(ReadCtx) *Rerror PostReadReplyHeader(ReadCtx) *Rerror PreReadReplyBody(ReadCtx) *Rerror PostReadReplyBody(ReadCtx) *Rerror PostDisconnect(PostSession) *Rerror // contains filtered or unexported methods }
PluginContainer plugin container that defines base methods to manage plugins.
type PostAcceptPlugin ¶
type PostAcceptPlugin interface { Plugin PostAccept(PreSession) *Rerror }
Interfaces about plugin.
type PostDialPlugin ¶
type PostDialPlugin interface { Plugin PostDial(PreSession) *Rerror }
Interfaces about plugin.
type PostDisconnectPlugin ¶
type PostDisconnectPlugin interface { Plugin PostDisconnect(PostSession) *Rerror }
Interfaces about plugin.
type PostReadPullBodyPlugin ¶
Interfaces about plugin.
type PostReadPullHeaderPlugin ¶
Interfaces about plugin.
type PostReadPushBodyPlugin ¶
Interfaces about plugin.
type PostReadPushHeaderPlugin ¶
Interfaces about plugin.
type PostReadReplyBodyPlugin ¶
Interfaces about plugin.
type PostReadReplyHeaderPlugin ¶
Interfaces about plugin.
type PostRegPlugin ¶
Interfaces about plugin.
type PostSession ¶
type PostSession interface { // Id returns the session id. Id() string // Peer returns the peer. Peer() *Peer // RemoteIp returns the remote peer ip. RemoteIp() string // LocalIp returns the local peer ip. LocalIp() string // Public returns temporary public data of session(socket). Public() goutil.Map // PublicLen returns the length of public data of session(socket). PublicLen() int }
Session a connection session.
type PostWritePullPlugin ¶
Interfaces about plugin.
type PostWritePushPlugin ¶
Interfaces about plugin.
type PostWriteReplyPlugin ¶
Interfaces about plugin.
type PreReadHeaderPlugin ¶
Interfaces about plugin.
type PreReadPullBodyPlugin ¶
Interfaces about plugin.
type PreReadPushBodyPlugin ¶
Interfaces about plugin.
type PreReadReplyBodyPlugin ¶
Interfaces about plugin.
type PreSession ¶
type PreSession interface { // SetId sets the session id. SetId(newId string) // Close closes the session. Close() error // Id returns the session id. Id() string // IsOk checks if the session is ok. IsOk() bool // Peer returns the peer. Peer() *Peer // RemoteIp returns the remote peer ip. RemoteIp() string // LocalIp returns the local peer ip. LocalIp() string // ReadTimeout returns readdeadline for underlying net.Conn. SetReadTimeout(duration time.Duration) // WriteTimeout returns writedeadline for underlying net.Conn. SetWriteTimeout(duration time.Duration) // Public returns temporary public data of session(socket). Public() goutil.Map // PublicLen returns the length of public data of session(socket). PublicLen() int // Send sends packet to peer. Send(packet *socket.Packet) error // Receive receives a packet from peer. Receive(packet *socket.Packet) error }
Session a connection session.
type PreWritePullPlugin ¶
Interfaces about plugin.
type PreWritePushPlugin ¶
Interfaces about plugin.
type PreWriteReplyPlugin ¶
Interfaces about plugin.
type PullCmd ¶
type PullCmd struct {
// contains filtered or unexported fields
}
PullCmd the command of the pulling operation's response.
func (*PullCmd) CostTime ¶
CostTime returns the pulled cost time. If PeerConfig.CountTime=false, always returns 0.
type PullCtx ¶
type PullCtx interface { PushCtx SetBodyCodec(byte) SetMeta(key, value string) AddXferPipe(filterId ...byte) }
PullCtx request handler context. For example:
type HomePull struct{ PullCtx }
type PushCtx ¶
type PushCtx interface { Seq() uint64 GetBodyCodec() byte GetMeta(key string) []byte Uri() string Path() string RawQuery() string Query() url.Values Public() goutil.Map PublicLen() int Ip() string Peer() *Peer Session() Session }
PushCtx push handler context. For example:
type HomePush struct{ PushCtx }
type ReadCtx ¶
type ReadCtx interface { Input() *socket.Packet Public() goutil.Map PublicLen() int Ip() string Peer() *Peer Session() Session }
ReadCtx for reading packet.
type Rerror ¶
type Rerror struct { // Code error code Code int32 // Message error message to the user (optional) Message string // Detail error's detailed reason (optional) Detail string }
Rerror error only for reply packet
func NewRerrorFromMeta ¶
NewRerrorFromMeta creates a *Rerror from 'X-Reply-Error' metadata. Return nil if there is no 'X-Reply-Error' in metadata.
func (*Rerror) MarshalJSON ¶
MarshalJSON marshals Rerror into JSON, implements json.Marshaler interface.
func (*Rerror) UnmarshalJSON ¶
UnmarshalJSON unmarshals a JSON description of self.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router the router of pull or push.
func (*Router) SetUnknown ¶
SetUnknown sets the default handler, which is called when no handler for pull or push is found.
type Session ¶
type Session interface { // SetId sets the session id. SetId(newId string) // Close closes the session. Close() error // Id returns the session id. Id() string // IsOk checks if the session is ok. IsOk() bool // Peer returns the peer. Peer() *Peer // GoPull sends a packet and receives reply asynchronously. // If the args is []byte or *[]byte type, it can automatically fill in the body codec name. GoPull(uri string, args interface{}, reply interface{}, done chan *PullCmd, setting ...socket.PacketSetting) // Pull sends a packet and receives reply. // If the args is []byte or *[]byte type, it can automatically fill in the body codec name. Pull(uri string, args interface{}, reply interface{}, setting ...socket.PacketSetting) *PullCmd // Push sends a packet, but do not receives reply. // If the args is []byte or *[]byte type, it can automatically fill in the body codec name. Push(uri string, args interface{}, setting ...socket.PacketSetting) *Rerror // ReadTimeout returns readdeadline for underlying net.Conn. ReadTimeout() time.Duration // RemoteIp returns the remote peer ip. RemoteIp() string // LocalIp returns the local peer ip. LocalIp() string // ReadTimeout returns readdeadline for underlying net.Conn. SetReadTimeout(duration time.Duration) // WriteTimeout returns writedeadline for underlying net.Conn. SetWriteTimeout(duration time.Duration) // Socket returns the Socket. // Socket() socket.Socket // WriteTimeout returns writedeadline for underlying net.Conn. WriteTimeout() time.Duration // Public returns temporary public data of session(socket). Public() goutil.Map // PublicLen returns the length of public data of session(socket). PublicLen() int }
Session a connection session.
type SessionHub ¶
type SessionHub struct {
// contains filtered or unexported fields
}
SessionHub sessions hub
func (*SessionHub) Delete ¶
func (sh *SessionHub) Delete(id string)
Delete deletes the *session for a id.
func (*SessionHub) Get ¶
func (sh *SessionHub) Get(id string) (*session, bool)
Get gets *session by id. If second returned arg is false, mean the *session is not found.
func (*SessionHub) Len ¶
func (sh *SessionHub) Len() int
Len returns the length of the session hub. Note: the count implemented using sync.Map may be inaccurate.
func (*SessionHub) Random ¶
func (sh *SessionHub) Random() (*session, bool)
Random gets a *session randomly. If third returned arg is false, mean no *session is exist.
func (*SessionHub) Range ¶
func (sh *SessionHub) Range(fn func(*session) bool)
Range calls f sequentially for each id and *session present in the session hub. If fn returns false, stop traversing.
type UnknownPullCtx ¶
type UnknownPullCtx interface { UnknownPushCtx AddXferPipe(filterId ...byte) }
type UnknownPushCtx ¶
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
samples
|
|
Socket package provides a concise, powerful and high-performance TCP socket.
|
Socket package provides a concise, powerful and high-performance TCP socket. |
example/pb
Package pb is a generated protocol buffer package.
|
Package pb is a generated protocol buffer package. |