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.

70 lines
1.6 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/aceld/zinx/ziface"
  5. "github.com/aceld/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.8"))
  30. if err != nil {
  31. fmt.Println(err)
  32. }
  33. }
  34. //创建连接的时候执行
  35. func DoConnectionBegin(conn ziface.IConnection) {
  36. fmt.Println("DoConnecionBegin is Called ... ")
  37. err := conn.SendMsg(2, []byte("DoConnection BEGIN..."))
  38. if err != nil {
  39. fmt.Println(err)
  40. }
  41. }
  42. //连接断开的时候执行
  43. func DoConnectionLost(conn ziface.IConnection) {
  44. fmt.Println("DoConneciotnLost is Called ... ")
  45. }
  46. func main() {
  47. //创建一个server句柄
  48. s := znet.NewServer()
  49. //注册链接hook回调函数
  50. s.SetOnConnStart(DoConnectionBegin)
  51. s.SetOnConnStop(DoConnectionLost)
  52. //配置路由
  53. s.AddRouter(0, &PingRouter{})
  54. s.AddRouter(1, &HelloZinxRouter{})
  55. //开启服务
  56. s.Serve()
  57. }