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.

85 lines
2.1 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "zinx/ziface"
  5. "zinx/znet"
  6. )
  7. //ping test 自定义路由
  8. type PingRouter struct {
  9. znet.BaseRouter
  10. }
  11. //Ping Handle
  12. func (this *PingRouter) Handle(request ziface.IRequest) {
  13. fmt.Println("Call PingRouter Handle")
  14. //先读取客户端的数据,再回写ping...ping...ping
  15. fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
  16. err := request.GetConnection().SendBuffMsg(0, []byte("ping...ping...ping"))
  17. if err != nil {
  18. fmt.Println(err)
  19. }
  20. }
  21. type HelloZinxRouter struct {
  22. znet.BaseRouter
  23. }
  24. //HelloZinxRouter Handle
  25. func (this *HelloZinxRouter) Handle(request ziface.IRequest) {
  26. fmt.Println("Call HelloZinxRouter Handle")
  27. //先读取客户端的数据,再回写ping...ping...ping
  28. fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
  29. err := request.GetConnection().SendBuffMsg(1, []byte("Hello Zinx Router V0.10"))
  30. if err != nil {
  31. fmt.Println(err)
  32. }
  33. }
  34. //创建连接的时候执行
  35. func DoConnectionBegin(conn ziface.IConnection) {
  36. fmt.Println("DoConnecionBegin is Called ... ")
  37. //设置两个链接属性,在连接创建之后
  38. fmt.Println("Set conn Name, Home done!")
  39. conn.SetProperty("Name", "Aceld")
  40. conn.SetProperty("Home", "https://www.jianshu.com/u/35261429b7f1")
  41. err := conn.SendMsg(2, []byte("DoConnection BEGIN..."))
  42. if err != nil {
  43. fmt.Println(err)
  44. }
  45. }
  46. //连接断开的时候执行
  47. func DoConnectionLost(conn ziface.IConnection) {
  48. //在连接销毁之前,查询conn的Name,Home属性
  49. if name, err:= conn.GetProperty("Name"); err == nil {
  50. fmt.Println("Conn Property Name = ", name)
  51. }
  52. if home, err := conn.GetProperty("Home"); err == nil {
  53. fmt.Println("Conn Property Home = ", home)
  54. }
  55. fmt.Println("DoConneciotnLost is Called ... ")
  56. }
  57. func main() {
  58. //创建一个server句柄
  59. s := znet.NewServer()
  60. //注册链接hook回调函数
  61. s.SetOnConnStart(DoConnectionBegin)
  62. s.SetOnConnStop(DoConnectionLost)
  63. //配置路由
  64. s.AddRouter(0, &PingRouter{})
  65. s.AddRouter(1, &HelloZinxRouter{})
  66. //开启服务
  67. s.Serve()
  68. }