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.

441 lines
12 KiB

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