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.

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