You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
6.7 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. # Zinx
  2. ---
  3. [![License](https://img.shields.io/badge/License-GPL%202.0-blue.svg)](LICENSE)
  4. Zinx 是一个基于Golang的轻量级并发服务器框架
  5. ### 开发人员
  6. github:`aceld`(刘丹冰)
  7. github:`zhngcho`(张超)
  8. ## 一、写在前面
  9. 我们为什么要做Zinx,Golang目前在服务器的应用框架很多,但是应用在游戏领域或者其他长链接的领域的轻量级企业框架甚少。
  10. 设计Zinx的目的是我们可以通过Zinx框架来了解基于Golang编写一个TCP服务器的整体轮廓,让更多的Golang爱好者能深入浅出的去学习和认识这个领域。
  11. Zinx框架的项目制作采用编码和学习教程同步进行,将开发的全部递进和迭代思维带入教程中,而不是一下子给大家一个非常完整的框架去学习,让很多人一头雾水,不知道该如何学起。
  12. 教程会一个版本一个版本迭代,每个版本的添加功能都是微小的,让一个服务框架小白,循序渐进的曲线方式了解服务器框架的领域。
  13. 当然,最后希望Zinx会有更多的人加入,给我们提出宝贵的意见,让Zinx成为真正的解决企业的服务器框架!在此感谢您的关注!
  14. ## 二、初探Zinx架构
  15. ![1-Zinx框架.png](https://upload-images.jianshu.io/upload_images/11093205-21a249a83fec62e9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  16. ## 三、Zinx详细教程(代码教程同步更新)
  17. [《Zinx框架教程-基于Golang的轻量级并发服务器》](https://www.jianshu.com/p/23d07c0a28e5)
  18. ## 四、Zinx开发API文档
  19. ### 快速开始
  20. #### server
  21. 基于Zinx框架开发的服务器应用,主函数步骤比较精简,最多主需要3步即可。
  22. 1. 创建server句柄
  23. 2. 配置自定义路由及业务
  24. 3. 启动服务
  25. ```go
  26. func main() {
  27. //1 创建一个server句柄
  28. s := znet.NewServer()
  29. //2 配置路由
  30. s.AddRouter(0, &PingRouter{})
  31. //3 开启服务
  32. s.Serve()
  33. }
  34. ```
  35. 其中自定义路由及业务配置方式如下:
  36. ```go
  37. import (
  38. "fmt"
  39. "zinx/ziface"
  40. "zinx/znet"
  41. )
  42. //ping test 自定义路由
  43. type PingRouter struct {
  44. znet.BaseRouter
  45. }
  46. //Ping Handle
  47. func (this *PingRouter) Handle(request ziface.IRequest) {
  48. //先读取客户端的数据
  49. fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
  50. //再回写ping...ping...ping
  51. err := request.GetConnection().SendBuffMsg(0, []byte("ping...ping...ping"))
  52. if err != nil {
  53. fmt.Println(err)
  54. }
  55. }
  56. ```
  57. #### client
  58. Zinx的消息处理采用,`[MsgLength]|[MsgID]|[Data]`的封包格式
  59. ```go
  60. package main
  61. import (
  62. "fmt"
  63. "io"
  64. "net"
  65. "time"
  66. "zinx/znet"
  67. )
  68. /*
  69. 模拟客户端
  70. */
  71. func main() {
  72. fmt.Println("Client Test ... start")
  73. //3秒之后发起测试请求,给服务端开启服务的机会
  74. time.Sleep(3 * time.Second)
  75. conn,err := net.Dial("tcp", "127.0.0.1:7777")
  76. if err != nil {
  77. fmt.Println("client start err, exit!")
  78. return
  79. }
  80. for n := 3; n >= 0; n-- {
  81. //发封包message消息
  82. dp := znet.NewDataPack()
  83. msg, _ := dp.Pack(znet.NewMsgPackage(0,[]byte("Zinx Client Test Message")))
  84. _, err := conn.Write(msg)
  85. if err !=nil {
  86. fmt.Println("write error err ", err)
  87. return
  88. }
  89. //先读出流中的head部分
  90. headData := make([]byte, dp.GetHeadLen())
  91. _, err = io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
  92. if err != nil {
  93. fmt.Println("read head error")
  94. break
  95. }
  96. //将headData字节流 拆包到msg中
  97. msgHead, err := dp.Unpack(headData)
  98. if err != nil {
  99. fmt.Println("server unpack err:", err)
  100. return
  101. }
  102. if msgHead.GetDataLen() > 0 {
  103. //msg 是有data数据的,需要再次读取data数据
  104. msg := msgHead.(*znet.Message)
  105. msg.Data = make([]byte, msg.GetDataLen())
  106. //根据dataLen从io中读取字节流
  107. _, err := io.ReadFull(conn, msg.Data)
  108. if err != nil {
  109. fmt.Println("server unpack data err:", err)
  110. return
  111. }
  112. fmt.Println("==> Recv Msg: ID=", msg.Id, ", len=", msg.DataLen, ", data=", string(msg.Data))
  113. }
  114. time.Sleep(1*time.Second)
  115. }
  116. }
  117. ```
  118. ### Zinx配置文件
  119. ```json
  120. {
  121. "Name":"Zinx Game",
  122. "Host":"0.0.0.0",
  123. "TcpPort":8999,
  124. "MaxConn":3000,
  125. "WorkerPoolSize":10
  126. }
  127. ```
  128. `Name`:服务器应用名称
  129. `Host`:服务器IP
  130. `TcpPort`:服务器监听端口
  131. `MaxConn`:允许的客户端链接最大数量
  132. `WorkerPoolSize`:工作任务池最大工作Goroutine数量
  133. ### I.服务器模块Server
  134. ```go
  135. func NewServer () ziface.IServer
  136. ```
  137. 创建一个Zinx服务器句柄,该句柄作为当前服务器应用程序的主枢纽,包括如下功能:
  138. #### 1)开启服务
  139. ```go
  140. func (s *Server) Start()
  141. ```
  142. #### 2)停止服务
  143. ```go
  144. func (s *Server) Stop()
  145. ```
  146. #### 3)运行服务
  147. ```go
  148. func (s *Server) Serve()
  149. ```
  150. #### 4)注册路由
  151. ```go
  152. func (s *Server) AddRouter (msgId uint32, router ziface.IRouter)
  153. ```
  154. #### 5)注册链接创建Hook函数
  155. ```go
  156. func (s *Server) SetOnConnStart(hookFunc func (ziface.IConnection))
  157. ```
  158. #### 6)注册链接销毁Hook函数
  159. ```go
  160. func (s *Server) SetOnConnStop(hookFunc func (ziface.IConnection))
  161. ```
  162. ### II.路由模块
  163. ```go
  164. //实现router时,先嵌入这个基类,然后根据需要对这个基类的方法进行重写
  165. type BaseRouter struct {}
  166. //这里之所以BaseRouter的方法都为空,
  167. // 是因为有的Router不希望有PreHandle或PostHandle
  168. // 所以Router全部继承BaseRouter的好处是,不需要实现PreHandle和PostHandle也可以实例化
  169. func (br *BaseRouter)PreHandle(req ziface.IRequest){}
  170. func (br *BaseRouter)Handle(req ziface.IRequest){}
  171. func (br *BaseRouter)PostHandle(req ziface.IRequest){}
  172. ```
  173. ### III.链接模块
  174. #### 1)获取原始的socket TCPConn
  175. ```go
  176. func (c *Connection) GetTCPConnection() *net.TCPConn
  177. ```
  178. #### 2)获取链接ID
  179. ```go
  180. func (c *Connection) GetConnID() uint32
  181. ```
  182. #### 3)获取远程客户端地址信息
  183. ```go
  184. func (c *Connection) RemoteAddr() net.Addr
  185. ```
  186. #### 4)发送消息
  187. ```go
  188. func (c *Connection) SendMsg(msgId uint32, data []byte) error
  189. func (c *Connection) SendBuffMsg(msgId uint32, data []byte) error
  190. ```
  191. #### 5)链接属性
  192. ```go
  193. //设置链接属性
  194. func (c *Connection) SetProperty(key string, value interface{})
  195. //获取链接属性
  196. func (c *Connection) GetProperty(key string) (interface{}, error)
  197. //移除链接属性
  198. func (c *Connection) RemoveProperty(key string)
  199. ```
  200. ---
  201. ### 关于作者:
  202. 作者:`Aceld(刘丹冰)`
  203. 简书号:`IT无崖子`
  204. `mail`:
  205. [danbing.at@gmail.com](mailto:danbing.at@gmail.com)
  206. `github`:
  207. [https://github.com/aceld](https://github.com/aceld)
  208. `原创书籍gitbook`:
  209. [http://legacy.gitbook.com/@aceld](http://legacy.gitbook.com/@aceld)
  210. ### Zinx技术讨论社区
  211. QQ技术讨论群:
  212. ![gopool5.jpeg](https://upload-images.jianshu.io/upload_images/11093205-6cdfd381e8ffa127.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  213. 欢迎大家加入,获取更多相关学习资料