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.2 KiB

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