client-wsv2.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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/wsv2"
  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) (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())
  39. })
  40. // 订阅频道
  41. hub.Subscribe(&tinymq.SubscribeData{
  42. Channel: regexp.MustCompile(remoteChannel),
  43. Cmd: "hello",
  44. BackFunc: func(request *tinymq.RequestData) (state uint8, result []byte) {
  45. log.Println("[client RECV]<-", string(request.Data))
  46. return 1, []byte("tiny client")
  47. },
  48. })
  49. hub.Subscribe(&tinymq.SubscribeData{
  50. Channel: regexp.MustCompile(remoteChannel),
  51. Cmd: "nodata",
  52. BackFunc: func(request *tinymq.RequestData) (state uint8, result []byte) {
  53. log.Println("[client RECV]<-", string(request.Data))
  54. return 1, nil
  55. },
  56. })
  57. err := hub.ConnectToServer(remoteChannel, true)
  58. if err != nil {
  59. log.Fatalln("[client ConnectToServer ERROR]", err)
  60. }
  61. // 获取信息
  62. rsp := hub.GetOne(&tinymq.GetData{
  63. Channel: regexp.MustCompile(remoteChannel),
  64. Cmd: "hello",
  65. Data: []byte("hello from client"),
  66. })
  67. if rsp.State != config.STATE_OK {
  68. log.Println("error state:", rsp.State)
  69. return
  70. }
  71. log.Println("[RESULT]<-", string(rsp.Data))
  72. time.Sleep(time.Second * 300)
  73. log.Println("client exit")
  74. }