xtcp

package module
v0.0.0-...-838c0e2 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2018 License: MIT Imports: 8 Imported by: 2

README

xtcp

A TCP Server Framework with graceful shutdown,custom protocol.

Build Status Go Report Card GoDoc

Install

go get github.com/xfxdev/xlog // xtcp use xlog inner.
go get github.com/xfxdev/xtcp

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)
}
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
	// EventSend mean conn send a packet.
	EventSend
	// 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.
// note : ListenAndServe is a **block** function, if you don't want block, just run it in a goroutine.
// go function() {
//     server.ListenAndServe("addr")
// }()
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
// note : DialAndServe is a **block** function, if you don't want block, just run it in a goroutine.
// go function() {
//     client.DialAndServe("addr")
// }()
client.DialAndServe("addr")
send and recv packet.

To send a packet, just call the 'Send' function of Conn. You can safe call it in any goroutines. Note : Conn has a packets channel for send, so Send will block when the packets channel is full. You can set the channel length in the Options when create server or client.

func (c *Conn) Send(p Packet) 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 the packets in the send channel sended.

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

const (
	// StopImmediately mean stop directly.
	StopImmediately StopMode = iota
	// StopGracefullyButNotWait mean stop gracefully but not wait.
	StopGracefullyButNotWait
	// StopGracefullyAndWait mean stop and wait.
	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 (
	// ErrNoMemory is passed to panic if memory cannot be allocated to store data in a buffer.
	ErrNoMemory = errors.New("xtcp.buffer: no memory")
	// ErrSpaceLimit means that the required space beyond the upper limit.
	ErrSpaceLimit = errors.New("xtcp.buffer: required space beyond the upper limit")
	// ErrNegativeCount means that negative count.
	ErrNegativeCount = errors.New("xtcp.buffer: negative count")
)
View Source
var (
	// DefaultSendListLen is the default length of send list.
	DefaultSendListLen = 16 // channel size
	// DefaultRecvBufInitSize is the default init size of recv buf.
	DefaultRecvBufInitSize = 1 << 10 // 1k
	// DefaultRecvBufMaxSize is the default max size of recv buf.
	DefaultRecvBufMaxSize = 4 << 10 // 4k
	// DefaultSendBufInitSize is the default init size of send buf.
	DefaultSendBufInitSize = 1 << 10 // 1k
	// DefaultSendBufMaxSize is the default max size of send buf.
	DefaultSendBufMaxSize = 2 << 10 // 4k
)

Functions

This section is empty.

Types

type Buffer

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

A Buffer is a variable-sized buffer of bytes.

func NewBuffer

func NewBuffer(initSize, maxSize int) *Buffer

NewBuffer create a new Buffer. If initSize == 0 or initSize > maxSize it will return nil. If create buffer failed it will panic with ErrNoMemory.

func (*Buffer) Advance

func (b *Buffer) Advance(n int) ([]byte, error)

Advance discard the n bytes from the last read. If n is negative return errNegativeCount. If the buffer can't advance it will return ErrSpaceLimit.

func (*Buffer) Cap

func (b *Buffer) Cap() int

Cap returns the capacity of the buffer's underlying byte slice, that is, the total space allocated for the buffer's data.

func (*Buffer) Grow

func (b *Buffer) Grow(n int) error

Grow grows the buffer's capacity until to max size. After Grow(n), at least n bytes can be written to the buffer without another allocation. return ErrNegativeCount if n is negative. return ErrSpaceLimit if need space size grater than the max size. If the buffer can't alloc memory it will panic with ErrNoMemory.

func (*Buffer) TryRead

func (b *Buffer) TryRead(r io.Reader) (int, error)

TryRead reads data from r to the remain space.

func (*Buffer) UnreadBytes

func (b *Buffer) UnreadBytes() []byte

UnreadBytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification.

func (*Buffer) UnreadLen

func (b *Buffer) UnreadLen() int

UnreadLen return the length of unread bytes.

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (int, error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; return error will be ErrSpaceLimit if need space size grater than the max size. If the buffer can't alloc memory it will panic with ErrNoMemory.

type Conn

type Conn struct {
	Opts     *Options
	RawConn  net.Conn
	UserData interface{}
	// 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) IsStoped

func (c *Conn) IsStoped() bool

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

func (*Conn) Send

func (c *Conn) Send(p Packet) error

Send will use the protocol to pack the Packet.

func (*Conn) Stop

func (c *Conn) Stop(mode StopMode)

Stop stops the conn. StopImmediately: immediately closes recv and send. StopGracefullyButNotWait: stop accept new send, but all send bufs in the send list will continue send. StopGracefullyAndWait: stop accept new send, will block until all send bufs in the send list are sended.

func (*Conn) String

func (c *Conn) String() string

type EventType

type EventType int

EventType is the conn event type.

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

func (EventType) String

func (et EventType) String() string

type Handler

type Handler interface {
	OnEvent(et EventType, c *Conn, p Packet)
}

Handler is the event callback. p will be nil when event is EventAccept/EventConnected/EventClosed

type Options

type Options struct {
	Handler         Handler
	Protocol        Protocol
	SendListLen     int // default is DefaultSendListLen if you don't set.
	RecvBufInitSize int // default is DefaultRecvBufInitSize if you don't set.
	RecvBufMaxSize  int // default is DefaultRecvBufMaxSize if you don't set.
	SendBufInitSize int // default is DefaultSendBufInitSize if you don't set.
	SendBufMaxSize  int // default is DefaultSendBufMaxSize if you don't set.
}

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)...

func (*Options) SetRecvBufInitSize

func (opts *Options) SetRecvBufInitSize(s int) *Options

SetRecvBufInitSize set init size of the recv buf, 0 mean DefaultRecvBufInitSize.

func (*Options) SetRecvBufMaxSize

func (opts *Options) SetRecvBufMaxSize(s int) *Options

SetRecvBufMaxSize set max size of the recv buf, 0 mean DefaultRecvBufMaxSize.

func (*Options) SetSendBufInitSize

func (opts *Options) SetSendBufInitSize(s int) *Options

SetSendBufInitSize set init size of the recv buf, 0 mean DefaultSendBufInitSize.

func (*Options) SetSendBufMaxSize

func (opts *Options) SetSendBufMaxSize(s int) *Options

SetSendBufMaxSize set max size of the recv buf, 0 mean DefaultSendBufMaxSize.

func (*Options) SetSendListLen

func (opts *Options) SetSendListLen(len int) *Options

SetSendListLen set init size of the recv buf, 0 mean DefaultSendListLen.

type Packet

type Packet interface {
	fmt.Stringer
}

Packet is the unit of data.

type Protocol

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)
}

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) 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 to accept new connections. StopGracefullyAndWait: stops the server to accept new connections and blocks until all connections are closed.

type StopMode

type StopMode uint8

StopMode define the stop mode of server and conn.

const (
	// StopImmediately mean stop directly.
	StopImmediately StopMode = iota
	// StopGracefullyButNotWait mean stop gracefully but not wait.
	StopGracefullyButNotWait
	// StopGracefullyAndWait mean stop and wait.
	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