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.

328 lines
9.3 KiB

6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
4 years ago
6 years ago
5 years ago
5 years ago
6 years ago
  1. # <img width="80px" src="https://s2.ax1x.com/2019/10/09/u4yHo9.png" />
  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. > **说明**:目前zinx已经在很多企业进行开发使用,具体使用领域包括:后端模块的消息中转、长链接游戏服务器、Web框架中的消息处理插件等。zinx的定位是代码简洁,让更多的开发者迅速的了解框架的内脏细节并且可以快速基于zinx DIY一款适合自己企业场景的模块。
  5. #### 开发者
  6. - 刘丹冰([@aceld](https://github.com/aceld))
  7. - 张超([@zhngcho](https://github.com/zhngcho))
  8. - 高智辉Roger([@adsian](https://github.com/adsian))
  9. ---
  10. [zinx(C++版本)](https://github.com/marklion/zinx)
  11. #### 开发者
  12. - 刘洋([@marklion](https://github.com/marklion))
  13. ---
  14. [zinx(Lua版本)](https://github.com/huqitt/zinx-lua)
  15. #### 开发者
  16. - 胡琪([@huqitt](https://github.com/huqitt))
  17. ---
  18. ## zinx源码地址
  19. ### Github
  20. Git: https://github.com/aceld/zinx
  21. ### 码云(Gitee)
  22. Git: https://gitee.com/Aceld/zinx
  23. ---
  24. ## 在线开发教程
  25. ### [B站]
  26. [![zinx-视频教程B站](https://s2.ax1x.com/2019/10/13/uv340S.jpg)](https://www.bilibili.com/video/av71067087)
  27. ### [YouTube]
  28. [![zinx-youtube](https://s2.ax1x.com/2019/10/14/KSurCR.jpg)](https://www.youtube.com/watch?v=U95iF-HMWsU&list=PL_GrAPKmuajzeNI8HBTi-k5NQO1g0rM-A)
  29. ## Zinx详细教程及文档
  30. ### PC端文档
  31. [《Zinx框架教程-基于Golang的轻量级并发服务器》](https://www.jianshu.com/p/23d07c0a28e5)
  32. ### 移动端文档
  33. ![gongzhonghao](https://s1.ax1x.com/2020/06/26/NrCHdf.jpg)
  34. ## 一、写在前面
  35. 我们为什么要做Zinx,Golang目前在服务器的应用框架很多,但是应用在游戏领域或者其他长链接的领域的轻量级企业框架甚少。
  36. 设计Zinx的目的是我们可以通过Zinx框架来了解基于Golang编写一个TCP服务器的整体轮廓,让更多的Golang爱好者能深入浅出的去学习和认识这个领域。
  37. Zinx框架的项目制作采用编码和学习教程同步进行,将开发的全部递进和迭代思维带入教程中,而不是一下子给大家一个非常完整的框架去学习,让很多人一头雾水,不知道该如何学起。
  38. 教程会一个版本一个版本迭代,每个版本的添加功能都是微小的,让一个服务框架小白,循序渐进的曲线方式了解服务器框架的领域。
  39. 当然,最后希望Zinx会有更多的人加入,给我们提出宝贵的意见,让Zinx成为真正的解决企业的服务器框架!在此感谢您的关注!
  40. **zinx荣誉**
  41. #### 开源中国GVP年度最有价值开源项目
  42. ![GVP-zinx](https://s2.ax1x.com/2019/10/13/uvYVBV.jpg)
  43. ## 二、初探Zinx架构
  44. ![1-Zinx框架.png](https://camo.githubusercontent.com/903d1431358fa6f4634ebaae3b49a28d97e23d77/68747470733a2f2f75706c6f61642d696d616765732e6a69616e7368752e696f2f75706c6f61645f696d616765732f31313039333230352d633735666636383232333362323533362e706e673f696d6167654d6f6772322f6175746f2d6f7269656e742f7374726970253743696d61676556696577322f322f772f31323430)
  45. ![zinx-start.gif](https://camo.githubusercontent.com/16afabf00523abd556d918203d11f413c178472a/68747470733a2f2f75706c6f61642d696d616765732e6a69616e7368752e696f2f75706c6f61645f696d616765732f31313039333230352d343930623439303938616336336166362e6769663f696d6167654d6f6772322f6175746f2d6f7269656e742f7374726970)
  46. ## 三、Zinx开发API文档
  47. ### 快速开始
  48. #### server
  49. 基于Zinx框架开发的服务器应用,主函数步骤比较精简,最多只需要3步即可。
  50. 1. 创建server句柄
  51. 2. 配置自定义路由及业务
  52. 3. 启动服务
  53. ```go
  54. func main() {
  55. //1 创建一个server句柄
  56. s := znet.NewServer()
  57. //2 配置路由
  58. s.AddRouter(0, &PingRouter{})
  59. //3 开启服务
  60. s.Serve()
  61. }
  62. ```
  63. 其中自定义路由及业务配置方式如下:
  64. ```go
  65. import (
  66. "fmt"
  67. "github.com/aceld/zinx/ziface"
  68. "github.com/aceld/zinx/znet"
  69. )
  70. //ping test 自定义路由
  71. type PingRouter struct {
  72. znet.BaseRouter
  73. }
  74. //Ping Handle
  75. func (this *PingRouter) Handle(request ziface.IRequest) {
  76. //先读取客户端的数据
  77. fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
  78. //再回写ping...ping...ping
  79. err := request.GetConnection().SendBuffMsg(0, []byte("ping...ping...ping"))
  80. if err != nil {
  81. fmt.Println(err)
  82. }
  83. }
  84. ```
  85. #### client
  86. Zinx的消息处理采用,`[MsgLength]|[MsgID]|[Data]`的封包格式
  87. ```go
  88. package main
  89. import (
  90. "fmt"
  91. "io"
  92. "net"
  93. "time"
  94. "github.com/aceld/zinx/znet"
  95. )
  96. /*
  97. 模拟客户端
  98. */
  99. func main() {
  100. fmt.Println("Client Test ... start")
  101. //3秒之后发起测试请求,给服务端开启服务的机会
  102. time.Sleep(3 * time.Second)
  103. conn,err := net.Dial("tcp", "127.0.0.1:7777")
  104. if err != nil {
  105. fmt.Println("client start err, exit!")
  106. return
  107. }
  108. for n := 3; n >= 0; n-- {
  109. //发封包message消息
  110. dp := znet.NewDataPack()
  111. msg, _ := dp.Pack(znet.NewMsgPackage(0,[]byte("Zinx Client Test Message")))
  112. _, err := conn.Write(msg)
  113. if err !=nil {
  114. fmt.Println("write error err ", err)
  115. return
  116. }
  117. //先读出流中的head部分
  118. headData := make([]byte, dp.GetHeadLen())
  119. _, err = io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
  120. if err != nil {
  121. fmt.Println("read head error")
  122. break
  123. }
  124. //将headData字节流 拆包到msg中
  125. msgHead, err := dp.Unpack(headData)
  126. if err != nil {
  127. fmt.Println("server unpack err:", err)
  128. return
  129. }
  130. if msgHead.GetDataLen() > 0 {
  131. //msg 是有data数据的,需要再次读取data数据
  132. msg := msgHead.(*znet.Message)
  133. msg.Data = make([]byte, msg.GetDataLen())
  134. //根据dataLen从io中读取字节流
  135. _, err := io.ReadFull(conn, msg.Data)
  136. if err != nil {
  137. fmt.Println("server unpack data err:", err)
  138. return
  139. }
  140. fmt.Println("==> Recv Msg: ID=", msg.Id, ", len=", msg.DataLen, ", data=", string(msg.Data))
  141. }
  142. time.Sleep(1*time.Second)
  143. }
  144. }
  145. ```
  146. ### Zinx配置文件
  147. ```json
  148. {
  149. "Name":"zinx v-0.10 demoApp",
  150. "Host":"127.0.0.1",
  151. "TcpPort":7777,
  152. "MaxConn":3,
  153. "WorkerPoolSize":10,
  154. "LogDir": "./mylog",
  155. "LogFile":"zinx.log"
  156. }
  157. ```
  158. `Name`:服务器应用名称
  159. `Host`:服务器IP
  160. `TcpPort`:服务器监听端口
  161. `MaxConn`:允许的客户端链接最大数量
  162. `WorkerPoolSize`:工作任务池最大工作Goroutine数量
  163. `LogDir`: 日志文件夹
  164. `LogFile`: 日志文件名称(如果不提供,则日志信息打印到Stderr)
  165. ### I.服务器模块Server
  166. ```go
  167. func NewServer () ziface.IServer
  168. ```
  169. 创建一个Zinx服务器句柄,该句柄作为当前服务器应用程序的主枢纽,包括如下功能:
  170. #### 1)开启服务
  171. ```go
  172. func (s *Server) Start()
  173. ```
  174. #### 2)停止服务
  175. ```go
  176. func (s *Server) Stop()
  177. ```
  178. #### 3)运行服务
  179. ```go
  180. func (s *Server) Serve()
  181. ```
  182. #### 4)注册路由
  183. ```go
  184. func (s *Server) AddRouter (msgId uint32, router ziface.IRouter)
  185. ```
  186. #### 5)注册链接创建Hook函数
  187. ```go
  188. func (s *Server) SetOnConnStart(hookFunc func (ziface.IConnection))
  189. ```
  190. #### 6)注册链接销毁Hook函数
  191. ```go
  192. func (s *Server) SetOnConnStop(hookFunc func (ziface.IConnection))
  193. ```
  194. ### II.路由模块
  195. ```go
  196. //实现router时,先嵌入这个基类,然后根据需要对这个基类的方法进行重写
  197. type BaseRouter struct {}
  198. //这里之所以BaseRouter的方法都为空,
  199. // 是因为有的Router不希望有PreHandle或PostHandle
  200. // 所以Router全部继承BaseRouter的好处是,不需要实现PreHandle和PostHandle也可以实例化
  201. func (br *BaseRouter)PreHandle(req ziface.IRequest){}
  202. func (br *BaseRouter)Handle(req ziface.IRequest){}
  203. func (br *BaseRouter)PostHandle(req ziface.IRequest){}
  204. ```
  205. ### III.链接模块
  206. #### 1)获取原始的socket TCPConn
  207. ```go
  208. func (c *Connection) GetTCPConnection() *net.TCPConn
  209. ```
  210. #### 2)获取链接ID
  211. ```go
  212. func (c *Connection) GetConnID() uint32
  213. ```
  214. #### 3)获取远程客户端地址信息
  215. ```go
  216. func (c *Connection) RemoteAddr() net.Addr
  217. ```
  218. #### 4)发送消息
  219. ```go
  220. func (c *Connection) SendMsg(msgId uint32, data []byte) error
  221. func (c *Connection) SendBuffMsg(msgId uint32, data []byte) error
  222. ```
  223. #### 5)链接属性
  224. ```go
  225. //设置链接属性
  226. func (c *Connection) SetProperty(key string, value interface{})
  227. //获取链接属性
  228. func (c *Connection) GetProperty(key string) (interface{}, error)
  229. //移除链接属性
  230. func (c *Connection) RemoveProperty(key string)
  231. ```
  232. ---
  233. ### 关于作者:
  234. 作者:`Aceld(刘丹冰)`
  235. `mail`:
  236. [danbing.at@gmail.com](mailto:danbing.at@gmail.com)
  237. `github`:
  238. [https://github.com/aceld](https://github.com/aceld)
  239. `原创书籍gitbook`:
  240. [http://legacy.gitbook.com/@aceld](http://legacy.gitbook.com/@aceld)
  241. ### Zinx技术讨论社区
  242. ### **微信公众号**
  243. ![gongzhonghao](https://s1.ax1x.com/2020/06/26/NrCHdf.jpg)
  244. ### **QQ资源分享**
  245. ![qqqun](https://s1.ax1x.com/2020/06/26/NrCbo8.th.png)
  246. ### **微信群**
  247. ![weixin](https://s1.ax1x.com/2020/06/26/NrCOJg.png){:height="50%" width="50%"}
  248. <img src="https://s1.ax1x.com/2020/06/26/NrCOJg.png" width = "200" height = "230" alt="weixin" />
  249. 欢迎大家加入,获取更多相关学习资料