client-tpv2.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //go:build ignore
  2. // +build ignore
  3. package main
  4. import (
  5. "log"
  6. "regexp"
  7. "time"
  8. "git.me9.top/git/tinymq"
  9. "git.me9.top/git/tinymq/config"
  10. )
  11. func main() {
  12. cf := config.NewConfig()
  13. channel := "/tinymq/client/tpv2"
  14. host := &tinymq.HostInfo{
  15. Proto: "tp",
  16. Version: 2,
  17. Host: "127.0.0.1",
  18. Port: 34222,
  19. Hash: "xor:1qaz2wsx3",
  20. }
  21. hub := tinymq.NewHub(cf, channel, func(channel string) (hostInfo *tinymq.HostInfo, err error) {
  22. return host, nil
  23. }, func(proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  24. // 从 remoteAuth 是否为空来判断是否需要返回信息
  25. if len(remoteAuth) <= 0 {
  26. // 客户端调用,返回验证信息
  27. return []byte("tinymq")
  28. } else {
  29. // 服务端调用,返回验证token,或者其他信息
  30. return nil
  31. }
  32. }, func(proto string, version uint8, channel string, auth []byte) bool {
  33. return string(auth) == "tinymq"
  34. }, func(conn *tinymq.Line) {
  35. log.Println("connect state", conn.State())
  36. })
  37. // 订阅频道
  38. hub.Subscribe(&tinymq.SubscribeData{
  39. Channel: regexp.MustCompile("/tinymq/server"),
  40. Cmd: "hello",
  41. BackFunc: func(request *tinymq.RequestData) (state uint8, result []byte) {
  42. log.Println("[client RECV]<-", string(request.Data))
  43. return 1, []byte("tiny client")
  44. },
  45. })
  46. hub.Subscribe(&tinymq.SubscribeData{
  47. Channel: regexp.MustCompile("/tinymq/server"),
  48. Cmd: "nodata",
  49. BackFunc: func(request *tinymq.RequestData) (state uint8, result []byte) {
  50. log.Println("[client RECV]<-", string(request.Data))
  51. return 1, nil
  52. },
  53. })
  54. err := hub.ConnectToServer("/tinymq/server", true)
  55. if err != nil {
  56. log.Fatalln("[client ConnectToServer ERROR]", err)
  57. }
  58. // 获取信息
  59. rsp := hub.GetOne(&tinymq.GetData{
  60. Channel: regexp.MustCompile("/tinymq/server"),
  61. Cmd: "hello",
  62. Data: []byte("hello from client"),
  63. })
  64. if rsp.State != config.STATE_OK {
  65. log.Println("error state:", rsp.State)
  66. return
  67. }
  68. log.Println("[RESULT]<-", string(rsp.Data))
  69. time.Sleep(time.Second * 300)
  70. log.Println("client exit")
  71. }