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.

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