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.

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