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.

399 lines
12 KiB

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