服务端API
server
基于Zinx框架开发的服务器应用,主函数步骤比较精简,最多只需要3步即可。
- 创建server句柄
- 配置自定义路由及业务
- 启动服务
1 2 3 4 5 6 7 8 9 10
| func main() { s := znet.NewServer()
s.AddRouter(0, &PingRouter{})
s.Serve() }
|
其中自定义路由及业务配置方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import ( "fmt" "github.com/aceld/zinx/ziface" "github.com/aceld/zinx/znet" )
type PingRouter struct { znet.BaseRouter }
func (this *PingRouter) Handle(request ziface.IRequest) { fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
err := request.GetConnection().SendBuffMsg(0, []byte("ping...ping...ping")) if err != nil { fmt.Println(err) } }
|
I.服务器模块Server
1
| func NewServer () ziface.IServer
|
创建一个Zinx服务器句柄,该句柄作为当前服务器应用程序的主枢纽,包括如下功能:
1)开启服务
1
| func (s *Server) Start()
|
2)停止服务
3)运行服务
1
| func (s *Server) Serve()
|
4)注册路由
1
| func (s *Server) AddRouter (msgId uint32, router ziface.IRouter)
|
5)注册链接创建Hook函数
1
| func (s *Server) SetOnConnStart(hookFunc func (ziface.IConnection))
|
6)注册链接销毁Hook函数
1
| func (s *Server) SetOnConnStop(hookFunc func (ziface.IConnection))
|
II.路由模块
1 2 3 4 5 6 7 8 9
| type BaseRouter struct {}
func (br *BaseRouter)PreHandle(req ziface.IRequest){} func (br *BaseRouter)Handle(req ziface.IRequest){} func (br *BaseRouter)PostHandle(req ziface.IRequest){}
|
III.链接模块
1)获取原始的socket TCPConn
1
| func (c *Connection) GetTCPConnection() *net.TCPConn
|
2)获取链接ID
1
| func (c *Connection) GetConnID() uint32
|
3)获取远程客户端地址信息
1
| func (c *Connection) RemoteAddr() net.Addr
|
4)发送消息
1 2
| func (c *Connection) SendMsg(msgId uint32, data []byte) error func (c *Connection) SendBuffMsg(msgId uint32, data []byte) error
|
5)链接属性
1 2 3 4 5 6 7 8
| func (c *Connection) SetProperty(key string, value interface{})
//获取链接属性 func (c *Connection) GetProperty(key string) (interface{}, error)
//移除链接属性 func (c *Connection) RemoveProperty(key string)
|