Aucuba

package module
v0.0.0-...-6c53c4d Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2020 License: MIT Imports: 10 Imported by: 0

README

     ___      __    __    ______  __    __  .______        ___      
    /   \    |  |  |  |  /      ||  |  |  | |   _  \      /   \     
   /  ^  \   |  |  |  | |  ,----'|  |  |  | |  |_)  |    /  ^  \    
  /  /_\  \  |  |  |  | |  |     |  |  |  | |   _  <    /  /_\  \   
 /  _____  \ |  `--'  | |  `----.|  `--'  | |  |_)  |  /  _____  \  
/__/     \__\ \______/   \______| \______/  |______/  /__/     \__\ 
                                                                    

Aucuba is a concise and lightweight socket framework

Overall structure

1

Install

go get github.com/JontyX/Aucuba

QuickStart

Server

Based on the server application developed by the Aucuba framework, the main function steps are relatively simple and only need 4 steps at most.

  • Create server handle
  • Register hook function
  • Configure custom routing and services
  • Start service
func main() {
	// create server handle
	s := Aucuba.NewServer()
	
    // Configure hook function
    s.SetOnConnStart(DoConnectionBegin)
	s.SetOnConnStop(DoConnectionLost)

	// Configure custom routing and services
	s.AddRouter(1, &HelloAucubaRouter{})

	// start service
	s.Serve()
}

Custom routing and hook configuration methods:

import (
	"fmt"
	"github.com/JontyX/Aucuba"
	"github.com/JontyX/Aucuba/aiface"
)

type HelloAucubaRouter struct {
	Aucuba.BaseRouter
}

//HelloAucubaRouter Handle
func (this *HelloAucubaRouter) Handle(request aiface.IRequest) {
	fmt.Println("Call HelloAucubaRouter Handle")
	fmt.Println("recv from client : msgId=", request.GetMsgId(), ", data=", string(request.GetData()))
	err := request.GetConnection().SendBuffMsg(1, []byte("Hello Aucuba Router V1.0"))
	if err != nil {
		fmt.Println(err)
	}
}

//Execute when the connection is created
func DoConnectionBegin(conn aiface.IConnection) {
	fmt.Println("DoConnecionBegin is Called ... ")
	err := conn.SendMsg(2, []byte("DoConnection BEGIN..."))
	if err != nil {
		fmt.Println(err)
	}
}

//Execute when the connection is disconnected
func DoConnectionLost(conn aiface.IConnection) {
	//Before the connection is destroyed, query the Name and Home properties of conn
	if name, err := conn.GetProperty("Name"); err == nil {
		fmt.Println("Conn Property Name = ", name)
	}
	if home, err := conn.GetProperty("Home"); err == nil {
		fmt.Println("Conn Property Home = ", home)
	}
	fmt.Println("DoConnection is called")
}
client

message processing uses the packet format of [MsgLength]|[MsgID]|[Data]

import (
	"fmt"
	"github.com/JontyX/Aucuba"
	"io"
	"net"
	"time"
)

/*
   simulate client
*/
func main() {
	fmt.Println("Client Test ... start")
	time.Sleep(3 * time.Second)
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client start err, exit!")
		return
	}
	for {
		//Send packet message
		dp := Aucuba.NewDataPack()
		msg, _ := dp.Pack(Aucuba.NewMsgPackage(0, []byte("Aucuba Client0 Test Message")))
		_, err := conn.Write(msg)
		if err != nil {
			fmt.Println("write error err ", err)
			return
		}
		//Read the head part of the stream first
		headData := make([]byte, dp.GetHeadLen())
		_, err = io.ReadFull(conn, headData)
		if err != nil {
			fmt.Println("read head error")
			break
		}
		//Unpack the headData byte stream into msg
		msgHead, err := dp.Unpack(headData)
		if err != nil {
			fmt.Println("server unpack err:", err)
			return
		}
		if msgHead.GetMsgLen() > 0 {
			msg := msgHead.(*Aucuba.Message)
			msg.Data = make([]byte, msg.GetMsgLen())
			//Read byte stream from io according to dataLen
			_, err := io.ReadFull(conn, msg.Data)
			if err != nil {
				fmt.Println("server unpack data err:", err)
				return
			}
			fmt.Println("==> Recv Msg: ID=", msg.Id, ", len=", msg.DataLen, ", data=", string(msg.Data))
		}
		time.Sleep(1 * time.Second)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewServer

func NewServer() aiface.IServer

Types

type BaseRouter

type BaseRouter struct {
}

func (*BaseRouter) Handle

func (br *BaseRouter) Handle(requst aiface.IRequest)

func (*BaseRouter) PostHandle

func (br *BaseRouter) PostHandle(requst aiface.IRequest)

func (*BaseRouter) PreHandle

func (br *BaseRouter) PreHandle(requst aiface.IRequest)

type ConnManager

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

Connection management module

func NewConnManager

func NewConnManager() *ConnManager

func (*ConnManager) Add

func (connMgr *ConnManager) Add(conn aiface.IConnection)

func (*ConnManager) ClearConn

func (connMgr *ConnManager) ClearConn()

func (*ConnManager) Get

func (connMgr *ConnManager) Get(connID uint32) (aiface.IConnection, error)

get connection by connID

func (*ConnManager) Len

func (connMgr *ConnManager) Len() int

func (*ConnManager) Remove

func (connMgr *ConnManager) Remove(conn aiface.IConnection)

type Connection

type Connection struct {
	TcpServer aiface.IServer

	// Currently connected socket
	Conn *net.TCPConn

	ConnID uint32

	//inform the channel that the current connection has exited and stopped
	ExitChan chan bool

	MsgHandler aiface.IMsgHandle
	// contains filtered or unexported fields
}

func NewConnection

func NewConnection(server aiface.IServer, conn *net.TCPConn, connID uint32, msgHandler aiface.IMsgHandle) *Connection

initialize the connection module

func (*Connection) GetConnID

func (c *Connection) GetConnID() uint32

func (*Connection) GetProperty

func (c *Connection) GetProperty(key string) (interface{}, error)

Get connection properties

func (*Connection) GetRemoteAddr

func (c *Connection) GetRemoteAddr() net.Addr

func (*Connection) GetTCPConnection

func (c *Connection) GetTCPConnection() *net.TCPConn

func (*Connection) RemoveProperty

func (c *Connection) RemoveProperty(key string)

remove connection properties

func (*Connection) SendBuffMsg

func (c *Connection) SendBuffMsg(msgId uint32, data []byte) error

func (*Connection) SendMsg

func (c *Connection) SendMsg(msgId uint32, data []byte) error

func (*Connection) SetProperty

func (c *Connection) SetProperty(key string, value interface{})

func (*Connection) Start

func (c *Connection) Start()

func (*Connection) StartReader

func (c *Connection) StartReader()

func (*Connection) StartWriter

func (c *Connection) StartWriter()

Send user's data to the client

func (*Connection) Stop

func (c *Connection) Stop()

type DataPack

type DataPack struct {
}

func NewDataPack

func NewDataPack() *DataPack

func (*DataPack) GetHeadLen

func (dp *DataPack) GetHeadLen() uint32

func (*DataPack) Pack

func (dp *DataPack) Pack(msg aiface.IMessage) ([]byte, error)

datalen|msgId|data

func (*DataPack) Unpack

func (dp *DataPack) Unpack(binaryData []byte) (aiface.IMessage, error)

将包的head信息读出,在根据datalen在读, 将二进制封装成Message

type Message

type Message struct {
	Id      uint32 //MsgID
	DataLen uint32 //the length of the data
	Data    []byte
}

func NewMsgPackage

func NewMsgPackage(id uint32, data []byte) *Message

func (*Message) GetData

func (m *Message) GetData() []byte

func (*Message) GetMegId

func (m *Message) GetMegId() uint32

func (*Message) GetMsgLen

func (m *Message) GetMsgLen() uint32

func (*Message) SetData

func (m *Message) SetData(data []byte)

func (*Message) SetDataLen

func (m *Message) SetDataLen(len uint32)

func (*Message) SetMsgId

func (m *Message) SetMsgId(id uint32)

type MsgHandle

type MsgHandle struct {
	// 存放每个MsgId所对应的处理方法
	Apis map[uint32]aiface.IRouter //存放每个MsgId 所对应的处理方法的map属性
	// worker池数量
	WorkerPoolSize uint32
	//Worker负责取任务的消息队列
	TaskQueue []chan aiface.IRequest
}

func NewMsgHandle

func NewMsgHandle() *MsgHandle

创建MsgHandle方法

func (*MsgHandle) AddRouter

func (mh *MsgHandle) AddRouter(msgId uint32, router aiface.IRouter)

为消息添加具体的处理逻辑

func (*MsgHandle) DoMsgHandler

func (mh *MsgHandle) DoMsgHandler(request aiface.IRequest)

马上以非阻塞方式处理消息

func (*MsgHandle) SendMsgToTaskQueue

func (mh *MsgHandle) SendMsgToTaskQueue(request aiface.IRequest)

将消息交给TaskQueue,由worker进行处理

func (*MsgHandle) StartOneWorker

func (mh *MsgHandle) StartOneWorker(workerID int, taskQueue chan aiface.IRequest)

func (*MsgHandle) StartWorkerPool

func (mh *MsgHandle) StartWorkerPool()

启动worker工作池

type Requst

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

func (*Requst) GetConnection

func (r *Requst) GetConnection() aiface.IConnection

func (*Requst) GetData

func (r *Requst) GetData() []byte

func (*Requst) GetMsgId

func (r *Requst) GetMsgId() uint32

type Server

type Server struct {
	Name string

	//IP version bound to the server
	IPVersion string

	IP string

	//The port the server is listening on
	Port int

	//connection manager of the current server
	ConnMgr aiface.IConnManager

	OnConnStart func(conn aiface.IConnection)

	OnConnStop func(conn aiface.IConnection)
	// contains filtered or unexported fields
}

func (*Server) AddRouter

func (s *Server) AddRouter(msgId uint32, router aiface.IRouter)

func (*Server) CallOnConnStart

func (s *Server) CallOnConnStart(conn aiface.IConnection)

Call the connection OnConnStart Hook function

func (*Server) CallOnConnStop

func (s *Server) CallOnConnStop(conn aiface.IConnection)

func (*Server) GetConnMgr

func (s *Server) GetConnMgr() aiface.IConnManager

func (*Server) Serve

func (s *Server) Serve()

func (*Server) SetOnConnStart

func (s *Server) SetOnConnStart(hookFunc func(aiface.IConnection))

func (*Server) SetOnConnStop

func (s *Server) SetOnConnStop(hookFunc func(aiface.IConnection))

func (*Server) Start

func (s *Server) Start()

func (*Server) Stop

func (s *Server) Stop()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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