xtcp

package module
v0.0.0-...-2a44c14 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2020 License: MIT Imports: 8 Imported by: 6

README

xtcp

A TCP Server Framework with graceful shutdown,custom protocol.

Build Status Go Report Card GoDoc

Usage

Define your protocol format:

Before create server and client, you need define the protocol format first.

// Packet is the unit of data.
type Packet interface {
	fmt.Stringer
}

// Protocol use to pack/unpack Packet.
type Protocol interface {
	// return the size need for pack the Packet.
	PackSize(p Packet) int
	// PackTo pack the Packet to w.
	// The return value n is the number of bytes written;
	// Any error encountered during the write is also returned.
	PackTo(p Packet, w io.Writer) (int, error)
	// Pack pack the Packet to new created buf.
	Pack(p Packet) ([]byte, error)
	// try to unpack the buf to Packet. If return len > 0, then buf[:len] will be discard.
	// The following return conditions must be implement:
	// (nil, 0, nil) : buf size not enough for unpack one Packet.
	// (nil, len, err) : buf size enough but error encountered.
	// (p, len, nil) : unpack succeed.
	Unpack(buf []byte) (Packet, int, error)
}
Set your logger(optional):
func SetLogger(l Logger)

Note: xtcp will not output any log by default unless you implement your own logger.

Provide event handler:

In xtcp, there are some events to notify the state of net conn, you can handle them according your need:

const (
	// EventAccept mean server accept a new connect.
	EventAccept EventType = iota
	// EventConnected mean client connected to a server.
	EventConnected
	// EventRecv mean conn recv a packet.
	EventRecv
	// EventClosed mean conn is closed.
	EventClosed
)

To handle the event, just implement the OnEvent interface.

// Handler is the event callback.
// p will be nil when event is EventAccept/EventConnected/EventClosed
type Handler interface {
	OnEvent(et EventType, c *Conn, p Packet)
}
Create server:
// 1. create protocol and handler.
// ...

// 2. create opts.
opts := xtcp.NewOpts(handler, protocol)

// 3. create server.
server := xtcp.NewServer(opts)

// 4. start.
go server.ListenAndServe("addr")
Create client:
// 1. create protocol and handler.
// ...

// 2. create opts.
opts := xtcp.NewOpts(handler, protocol)

// 3. create client.
client := NewConn(opts)

// 4. start
go client.DialAndServe("addr")
Send and recv packet.

To send data, just call the 'Send' function of Conn. You can safe call it in any goroutines.

func (c *Conn) Send(buf []byte) error

To recv a packet, implement your handler function:

func (h *myhandler) OnEvent(et EventType, c *Conn, p Packet) {
	switch et {
		case EventRecv:
			...
	}
}
Stop

xtcp have three stop modes, stop gracefully mean conn will stop until all cached data sended.

// StopMode define the stop mode of server and conn.
type StopMode uint8

const (
	// StopImmediately mean stop directly, the cached data maybe will not send.
	StopImmediately StopMode = iota
	// StopGracefullyButNotWait stop and flush cached data.
	StopGracefullyButNotWait
	// StopGracefullyAndWait stop and block until cached data sended.
	StopGracefullyAndWait
)

Example

The example define a protocol format which use protobuf inner. You can see how to define the protocol and how to create server and client.

example

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultRecvBufSize is the default size of recv buf.
	DefaultRecvBufSize = 4 << 10 // 4k
	// DefaultSendBufListLen is the default length of send buf list.
	DefaultSendBufListLen = 1 << 10 // 1k
	// DefaultAsyncWrite is enable async write or not.
	DefaultAsyncWrite = true
)

Functions

func SetLogger

func SetLogger(l Logger)

SetLogger set the logger

Types

type Conn

type Conn struct {
	sync.Mutex
	Opts     *Options
	RawConn  net.Conn
	UserData interface{}

	SendDropped uint32
	// contains filtered or unexported fields
}

A Conn represents the server side of an tcp connection.

func NewConn

func NewConn(opts *Options) *Conn

NewConn return new conn.

func (*Conn) DialAndServe

func (c *Conn) DialAndServe(addr string) error

DialAndServe connects to the addr and serve.

func (*Conn) DroppedPacket

func (c *Conn) DroppedPacket() uint32

DroppedPacket return the total dropped packet.

func (*Conn) IsStoped

func (c *Conn) IsStoped() bool

IsStoped return true if Conn is stopped, otherwise return false.

func (*Conn) RecvBytes

func (c *Conn) RecvBytes() uint64

RecvBytes return the total receive bytes.

func (*Conn) Send

func (c *Conn) Send(buf []byte) (int, error)

Send use for send data, can be call in any goroutines.

func (*Conn) SendBytes

func (c *Conn) SendBytes() uint64

SendBytes return the total send bytes.

func (*Conn) SendPacket

func (c *Conn) SendPacket(p Packet) (int, error)

SendPacket use for send packet, can be call in any goroutines.

func (*Conn) Stop

func (c *Conn) Stop(mode StopMode)

Stop stops the conn.

func (*Conn) String

func (c *Conn) String() string

type Handler

type Handler interface {
	// OnAccept mean server accept a new connect.
	OnAccept(*Conn)
	// OnConnect mean client connected to a server.
	OnConnect(*Conn)
	// OnRecv mean conn recv a packet.
	OnRecv(*Conn, Packet)
	// OnUnpackErr mean failed to unpack recved data.
	OnUnpackErr(*Conn, []byte, error)
	// OnClose mean conn is closed.
	OnClose(*Conn)
}

Handler is the event callback. Note : don't block in event handler.

type LogLevel

type LogLevel uint8

LogLevel used to filter log message by the Logger.

const (
	Panic LogLevel = iota
	Fatal
	Error
	Warn
	Info
	Debug
)

logging levels.

type Logger

type Logger interface {
	Log(l LogLevel, v ...interface{})
	Logf(l LogLevel, format string, v ...interface{})
}

Logger is the log interface

type Options

type Options struct {
	Handler         Handler
	Protocol        Protocol
	RecvBufSize     int           // default is DefaultRecvBufSize if you don't set.
	SendBufListLen  int           // default is DefaultSendBufListLen if you don't set.
	AsyncWrite      bool          // default is DefaultAsyncWrite  if you don't set.
	NoDelay         bool          // default is true
	KeepAlive       bool          // default is false
	KeepAlivePeriod time.Duration // default is 0, mean use system setting.
	ReadDeadline    time.Duration // default is 0, means Read will not time out.
	WriteDeadline   time.Duration // default is 0, means Write will not time out.
}

Options is the options used for net conn.

func NewOpts

func NewOpts(h Handler, p Protocol) *Options

NewOpts create a new options and set some default value. will panic if handler or protocol is nil. eg: opts := NewOpts().SetSendListLen(len).SetRecvBufInitSize(len)...

type Packet

type Packet interface {
	fmt.Stringer
}

Packet is the unit of data.

type Protocol

type Protocol interface {
	// PackSize return the size need for pack the Packet.
	PackSize(p Packet) int
	// PackTo pack the Packet to w.
	// The return value n is the number of bytes written;
	// Any error encountered during the write is also returned.
	PackTo(p Packet, w io.Writer) (int, error)
	// Pack pack the Packet to new created buf.
	Pack(p Packet) ([]byte, error)
	// Unpack try to unpack the buf to Packet. If return len > 0, then buf[:len] will be discard.
	// The following return conditions must be implement:
	// (nil, 0, nil) : buf size not enough for unpack one Packet.
	// (nil, len, err) : buf size enough but error encountered.
	// (p, len, nil) : unpack succeed.
	Unpack(buf []byte) (Packet, int, error)
}

Protocol use to pack/unpack Packet.

type Server

type Server struct {
	Opts *Options
	// contains filtered or unexported fields
}

Server used for running a tcp server.

func NewServer

func NewServer(opts *Options) *Server

NewServer create a tcp server but not start to accept. The opts will set to all accept conns.

func (*Server) CurClientCount

func (s *Server) CurClientCount() int

CurClientCount return current client count.

func (*Server) IsStopped

func (s *Server) IsStopped() bool

IsStopped check if server is stopped.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe listens on the TCP network address addr and then calls Serve to handle requests on incoming connections.

func (*Server) Serve

func (s *Server) Serve(l net.Listener)

Serve start the tcp server to accept.

func (*Server) Stop

func (s *Server) Stop(mode StopMode)

Stop stops the tcp server. StopImmediately: immediately closes all open connections and listener. StopGracefullyButNotWait: stops the server and stop all connections gracefully. StopGracefullyAndWait: stops the server and blocks until all connections are stopped gracefully.

type StopMode

type StopMode uint8

StopMode define the stop mode of server and conn.

const (
	// StopImmediately mean stop directly, the cached data maybe will not send.
	StopImmediately StopMode = iota
	// StopGracefullyButNotWait stop and flush cached data.
	StopGracefullyButNotWait
	// StopGracefullyAndWait stop and block until cached data sended.
	StopGracefullyAndWait
)

Directories

Path Synopsis
exampleproto
Package exampleproto is a generated protocol buffer package.
Package exampleproto is a generated protocol buffer package.

Jump to

Keyboard shortcuts

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