client-ws2.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. localChannel := "/tinymq/client/ws2"
  14. remoteChannel := "/tinymq/server"
  15. host := &tinymq.HostInfo{
  16. Proto: "ws",
  17. Version: 2,
  18. Host: "127.0.0.1",
  19. Port: 34211,
  20. // Path: "/tinymq",
  21. Path: "/tinymq-xor",
  22. Hash: "xor:1qaz2wsx3edc",
  23. }
  24. hub := tinymq.NewHub(cf, localChannel, func(channel string, hostType tinymq.HostType) (hostInfo *tinymq.HostInfo, err error) {
  25. return host, nil
  26. }, func(proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  27. // 从 remoteAuth 是否为空来判断是否需要返回信息
  28. if len(remoteAuth) <= 0 {
  29. // 客户端调用,返回验证信息
  30. return []byte("tinymq")
  31. } else {
  32. // 服务端调用,返回验证token,或者其他信息
  33. return nil
  34. }
  35. }, func(proto string, cversion uint8, hannel string, auth []byte) bool {
  36. return true
  37. }, func(conn *tinymq.Line) {
  38. log.Println("connect state", conn.Channel(), conn.State(), time.Since(conn.Updated()))
  39. })
  40. // 订阅频道
  41. hub.Subscribe(regexp.MustCompile(remoteChannel), "hello", 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(regexp.MustCompile(remoteChannel), "nodata", func(request *tinymq.RequestData) (state uint8, result []byte) {
  47. log.Println("[client RECV]<-", string(request.Data))
  48. return 1, nil
  49. },
  50. )
  51. err := hub.ConnectToServer(remoteChannel, true, nil)
  52. if err != nil {
  53. log.Fatalln("[client ConnectToServer ERROR]", err)
  54. }
  55. // 获取信息
  56. rsp := hub.GetOne(regexp.MustCompile(remoteChannel), "hello", []byte("hello from client,hello from client,hello from client"))
  57. if rsp.State != config.STATE_OK {
  58. log.Println("error state:", rsp.State)
  59. return
  60. }
  61. log.Println("[RESULT]<-", string(rsp.Data))
  62. // 获取长数据
  63. rsp = hub.GetOne(regexp.MustCompile(remoteChannel), "bigdata", nil)
  64. if rsp.State != config.STATE_OK {
  65. log.Println("error state:", rsp.State)
  66. return
  67. } else {
  68. log.Println("get bigdata ok")
  69. }
  70. time.Sleep(time.Second * 5)
  71. hub.Push(regexp.MustCompile(remoteChannel), "push", []byte(time.Now().GoString()))
  72. time.Sleep(time.Second * 300)
  73. log.Println("client exit")
  74. }